我在操作下面的数组时遇到了一些困难。我尝试了各种各样的东西,我觉得应该有一个简单的方法来实现这一点,但我似乎无法弄明白。任何提示或帮助非常感谢,谢谢!
Array
(
[0] => Array
(
[0] => Array
(
[Color] => Blue
)
[1] => Array
(
[Size] => S
)
)
[1] => Array
(
[0] => Array
(
[Color] => Blue
)
[1] => Array
(
[Size] => M
)
)
)
我期望的结果是:
Array
(
[0] => Array
(
[Color] => Blue
[Size] => S
)
[1] => Array
(
[Color] => Blue
[Size] => M
)
)
答案 0 :(得分:3)
这有效:
$items = array(
array(
array("Color" => "Blue"),
array("Size" => "S")
),
array(
array("Color" => "Blue"),
array("Size" => "M")
)
);
$new_items = array();
foreach ($items as $item) {
$collect = array();
foreach ($item as $values) {
foreach ($values as $key => $value) {
$collect[$key] = $value;
}
}
$new_items[] = $collect;
}
var_dump($new_items);
你的数组是3深,所以你需要至少3个嵌套循环。
输出:
array(2) {
[0]=>
array(2) {
["Color"]=>
string(4) "Blue"
["Size"]=>
string(1) "S"
}
[1]=>
array(2) {
["Color"]=>
string(4) "Blue"
["Size"]=>
string(1) "M"
}
}
答案 1 :(得分:2)
array_merge
就足够了2个循环$a = array(
array(
array(
'Color' => 'Blue'
),
array(
'Size' => 'S'
),
),
array(
array(
'Color' => 'Blue'
),
array(
'Size' => 'M'
),
),
);
$c = array();
foreach($a as $b)
{
$ca = array();
if(is_array($b))
{
foreach($b as $array)
{
$ca = array_merge($ca, $array);
}
$c[] = $ca;
}
}
echo '<pre>'.print_r($c,true);
答案 2 :(得分:1)
您可以使用array_map:
<?php
function combine($elementArray)
{
return array($elementArray[0]["Color"], $elementArray[1]['Size']);
}
$originalArray = array(
0 => array(
0 => array("Color" => "Blue"),
1 => array("Size" => "S")
),
1 => array(
0 => array( "Color" => "Blue"),
1 => array("Size" => "M")
)
);
$combinedArray = array_map("combine", $originalArray);
echo "<pre>";
print_r($combinedArray);
?>
此外,你可以使用匿名函数,像专业人士一样;)
$combinedArray = array_map(
function($element){
return array(
"Color" => $element[0]["Color"],
"Size" => $element[1]['Size']
);
},$originalArray);
或者您甚至可以使用array_reduce示例:
$reducedArray = array_reduce($originalArray, function($result, $item){
$result[] = array(
'Color' => $item[0]['Color'],
'Size' => $item[1]['Size']
);
return $result;
});
答案 3 :(得分:0)
希望这会有所帮助
$array =
array(
array(
array(
'color'=>'Blue'
),
array(
'size'=>'s'
)
),
array(
array(
'color'=>'Red'
),
array(
'size'=>'m'
)
)
);
$mA = array();
foreach($array as $k=>$a){
array_push($mA,array_merge($a[0],$a[1]));
}
var_dump($mA);