[英]How to separated key values with same index in a new multidimensional array
I have below multidimensional array and need help to convert multidimensional in the specific formation 我在多维数组下面,需要帮助以特定形式转换多维
Array
(
[0] => Array
(
[0] => 20
[1] => 15
[2] => 0
)
[1] => Array
(
[0] => 28
[1] => 45
[2] => 0
)
[2] => Array
(
[0] => 20
[1] => 5
[2] => 50
)
[3] => Array
(
[0] => 48
[1] => 20
[2] => 0
)
)
and want to convert like this: 并想要这样转换:
Array
(
[0] => Array
(
[0] => 20
[1] => 28
[2] => 20
[3] => 48
)
[1] => Array
(
[0] => 15
[1] => 45
[2] => 5
[3] => 20
)
[2] => Array
(
[0] => 0
[1] => 0
[2] => 50
[3] => 0
)
)
On the above output, I have separated key values with the same index in a new array. 在上面的输出中,我在新数组中分离了具有相同索引的键值。
Is it possible? 可能吗?
Here is one of the solutions: 这是解决方案之一:
<?php
$array =
[
0 =>
[
0 => 20,
1 => 15,
2 => 0
],
1 =>
[
0 => 28,
1 => 45,
2 => 0
],
2 =>
[
0 => 20,
1 => 5,
2 => 50
],
3 =>
[
0 => 48,
1 => 20,
2 => 0
]
];
$result = [];
echo '<pre>';
foreach ($array as $key => $value) {
for ($i = 0; $i<count($value); $i++) {
$result[$i][] = $value[$i];
}
}
var_dump($result);
Result: 结果:
array(3) {
[0]=>
array(4) {
[0]=>
int(20)
[1]=>
int(28)
[2]=>
int(20)
[3]=>
int(48)
}
[1]=>
array(4) {
[0]=>
int(15)
[1]=>
int(45)
[2]=>
int(5)
[3]=>
int(20)
}
[2]=>
array(4) {
[0]=>
int(0)
[1]=>
int(0)
[2]=>
int(50)
[3]=>
int(0)
}
}
This code is working fine and doing what you are looking for, try to copy paste on the editor and run it. 这段代码运行良好,可以完成您想要的工作,尝试在编辑器上复制粘贴并运行它。
<?php
$originalArray = Array(
Array
(
20,
15,
0
),
Array
(
28,
45,
0
),
Array
(
20,
5,
50
),
Array
(
48,
20,
0
)
); //echo"<pre>";print_R($originalArray); 00 10 20 30 40 : 01,11,21,31 : 02,12,22,32,
$newArray =array();
//echo count($originalArray);
//echo count($originalArray[1]);
$count = array_map('count', $originalArray);
$min = array_keys($count , max($count))[0];
$largest_arr = $originalArray[$min];
for($i=0;$i<count($largest_arr);$i++){
array_push($newArray,$originalArray[$i]);
for($j=0;$j<count($originalArray);$j++){
echo $j."--".$i."---".count($originalArray)."----".$originalArray[$j][$i]."<br>";
array_push($newArray[$i],$originalArray[$j][$i]);
}
}
echo "<pre>";print_R($newArray);
?>
I have found the solution from the PHP - how to flip the rows and columns of a 2D array post 我已经从PHP找到了解决方案-如何翻转2D数组帖子的行和列
$out = array();
foreach ($array as $rowkey => $row) {
foreach($row as $colkey => $col){
$out[$colkey][$rowkey]=$col;
}
}
This works perfectly for me. 这对我来说非常合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.