我有以下数组。 (一个var_dump输出)我想将这些相同的键元素组合到单个数组中。我怎么做?
array (size=3)
'totals' =>
array (size=3)
0 =>
array (size=1)
'total' => string '4' (length=1)
1 =>
array (size=1)
'total' => string '50' (length=2)
2 =>
array (size=1)
'total' => string '44' (length=2)
'styles' =>
array (size=3)
0 =>
array (size=1)
'style' => string '11' (length=2)
1 =>
array (size=1)
'style' => string 'aaa' (length=3)
2 =>
array (size=1)
'style' => string 'bb' (length=3)
'colors' =>
array (size=3)
0 =>
array (size=1)
'color' => string '11' (length=2)
1 =>
array (size=1)
'color' => string 'ccc' (length=3)
2 =>
array (size=1)
'color' => string 'ddd' (length=3)
最终输出应该是,
'totals' =>
array (size=3)
0 =>
array (size=1)
'total' => string '4' (length=1)
'style' => string '11' (length=2)
'color' => string '11' (length=2)
'styles' =>
array (size=3)
1 =>
array (size=1)
'total' => string '50' (length=2)
'style' => string 'aaa' (length=3)
'color' => string 'bb' (length=3)
'colors' =>
array (size=3)
2 =>
array (size=1)
'total' => string '44' (length=2)
'style' => string 'ccc' (length=3)
'color' => string 'ddd' (length=3)
答案 0 :(得分:1)
试试这个:
注意:它不是维持密钥=>成为数字数组,但功能。
$array = array("total"=>array(array("total"=>1),array("total"=>2),array("total"=>3)),
"styles"=>array(array("style"=>4),array("style"=>52),array("style"=>6)),
"colors"=>array(array("color"=>7),array("color"=>8),array("color"=>9))
);
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
输出:
Array
(
[0] => Array
(
[0] => Array
(
[total] => 1
)
[1] => Array
(
[style] => 4
)
[2] => Array
(
[color] => 7
)
)
[1] => Array
(
[0] => Array
(
[total] => 2
)
[1] => Array
(
[style] => 52
)
[2] => Array
(
[color] => 8
)
)
[2] => Array
(
[0] => Array
(
[total] => 3
)
[1] => Array
(
[style] => 6
)
[2] => Array
(
[color] => 9
)
)
)
答案 1 :(得分:0)
for ($j=0; $j < count($your_array) ; $j++) {
for ($k=0; $k < count($your_array[0]) ; $k++) {
if(!isset($sum[$k]))
{
$sum[$k]=0;
}else{
$sum[$k]=$sum[$k]+$your_array[$j][$k];
}
}
}
所以同样的关键wilbe结合在一起,无论大小如何:)