[英]PHP: put array entries in new order
I try to take the following array: 我尝试采用以下数组:
Array
(
[0] => Array
(
[1] => 12
[2] => 21
[3] => 33
)
[1] => Array
(
[1] => 5
[2] => 5
[3] => 4
)
[2] => Array
(
[1] => 1
[2] => 10
[3] => 11
)
[3] => Array
(
[3] => 2
)
) )
and create a new array with it, taking the first entries of the source array. 并使用它创建一个新数组,并获取源数组的第一个条目。 So the first array from this one would look like this:
因此,第一个数组看起来像这样:
Array
(
[0] => 12
[1] => 5
[2] => 1
[3] => 2
)
And the second one obviously like this: 第二个显然是这样的:
Array
(
[0] => 21
[1] => 5
[2] => 10
)
I tried around with 2 for loops, it somewhat works with 我尝试了2 for循环,它与
for ($i = 1; $i < count($month_array[$i]) + 1; $i++)
{
unset($temp_array);
for ($i2 = 0; $i2 < count($month_array); $i2++)
{
if (isset($month_array[$i2][$i]))
{
$temp_array[] = $month_array[$i2][$i];
}
}
}
But it leaves out some of the elements and if the source array is not complete, meaning only the 3rd array has a value for key 3, it also fails. 但是它会忽略一些元素,如果源数组不完整,这意味着只有第三个数组具有键3的值,它也会失败。 Any help ?
有什么帮助吗? Many thanks !
非常感谢 !
Try it like this: 像这样尝试:
$org_array = array(array(1 => 12,2 => 21,3 => 33),array(1 => 5,2 => 5,3 => 4),array(1 => 1,2 => 10,3 => 11),array(3 => 2),); // your original array
$new_array = array(); // the output array
foreach($org_array as $sub_org_value) { // for each sub array of your original array do this
foreach($sub_org_value as $key => $value) { // for each entry in a sub array do this
$new_array[$key][] = $value; // add the entry into the new_array in the right sub array
}
}
print_r($new_array[1]); // yields 12,5,1
print_r($new_array[2]); // yields 21,5,10
print_r($new_array[3]); // yields 33,4,11,2
Afterwards you have an array $new_array
that contains three arrays. 之后,您将获得一个包含三个数组的数组
$new_array
。 The first sub array has all 1 values, the second sub array has all 2 values and the third sub array has all 3 values. 第一个子数组具有所有1个值,第二个子数组具有所有2个值,第三个子数组具有所有3个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.