问题
Is there an efficient way to change the structure of this multidimensional array? I want to group the column values.
//$arrayBefore
[[5, 4, 10], [11, 13, 15], [32, 14, 15]];
Desired result:
//$arrayAfter
[[5, 11, 32], [4, 13, 14], [10, 15, 15]];
回答1:
You can do it based on array_column():-
<?php
$array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
$final_array = [array_column($array,0),array_column($array,1),array_column($array,2)];
print_r($final_array );
Output:-https://eval.in/836310
Note:- above code will work only for this array.
More general and considering all aspects code is using foreach()
:-
<?php
$array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
$final_array = array();
foreach($array as $arr){
foreach($arr as $key=>$value){
$final_array[$key][]=$value;
}
}
print_r($final_array);
Output:- https://eval.in/836313
回答2:
<?php
$array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
for($i = 0; $i < count($array); $i++) {
for ($j = 0; $j < count($array[$i]); $j++) {
$temp[$j][] = $array[$i][$j];
}
}
print_r($temp);
OUTPUT: http://www.phpwin.org/s/BVxAx3
回答3:
If you're unsure of the array structure, you can also use foreach. Will work for more than 3 in each arrays with out any code modification
<?
$arr = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];
foreach($arr as $value_arr){
$i=0;
foreach($value_arr as $value){
if ($value){
$arr2[$i][]=$value;
$i++;
}
}
}
echo "<pre>";
print_r($arr2);
echo "</pre>";
?>
Array
(
[0] => Array
(
[0] => 5
[1] => 11
[2] => 32
)
[1] => Array
(
[0] => 4
[1] => 13
[2] => 14
)
[2] => Array
(
[0] => 10
[1] => 15
[2] => 15
)
)
回答4:
I've already been mocked on SO for promoting a variadic approach for this kind of question, but I think it is important to show what the clever developers of php have afforded coders to do.
The ...
(splat operator) tells array_map()
that a multi-dimensional (with a potentially variable number of subarrays) array is coming. The function then synchronously iterates each individual subarray.
In the following code, I have commented out a method that statically names the arguments $v1
,$v2
,$v3
used by array_map()
. This will work for the OP's case.
The line of code following the commented one, is a method that dynamically accesses the values without needing to do any variable naming. This will also be hugely flexible for any case where the structure of the multi-dimensional array changes its size/shape.
PHP Manual references:
- variadic functions
- func_get_args()
One-liner (requires PHP5.6+): (Demo with additional examples/considerations)
$m_array=[[5, 4, 10], [11, 13, 15], [32, 14, 15]];
//$new=array_map(function($v1,$v2,$v3){return [$v1,$v2,$v3];},...$m_array);
$new=array_map(function(){return func_get_args();},...$m_array);
var_export($new);
Output:
array (
0 =>
array (
0 => 5,
1 => 11,
2 => 32,
),
1 =>
array (
0 => 4,
1 => 13,
2 => 14,
),
2 =>
array (
0 => 10,
1 => 15,
2 => 15,
),
)
来源:https://stackoverflow.com/questions/45257772/how-to-restructure-multi-dimensional-array-with-columns-as-rows