我在数组值中有数组,如下所示。
Array
(
[0] => Array
(
[0] => Array
(
[Floor] => Floor-1
)
[1] => Array
(
[Flat] => Flat A2
)
[2] => Array
(
[Area] => Balcony,
)
)
)
我需要将其设为单关联数组,如下所示。
Array
(
[0] => Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
)
我该怎么做?
答案 0 :(得分:3)
这个例子可以帮到你。
<?php
$arr = array(
array(
'floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
输出
Array
(
[floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
这里我们创建了一个名为$final_array
的空数组,我们将使用foreach
循环追加此数组。
请记住,如果你有一个相同的数组键,那么最后一个值将覆盖如下。
<?php
$arr = array(
array(
'floor'=>'Floor-1',
'floor'=>'Floor-2',
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
array(
'Area'=>'Balcony2,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
现在,输出将是
Array
(
[floor] => Floor-2
[Flat] => Flat A2
[Area] => Balcony2,
)
答案 1 :(得分:2)
<?php
$array = [
[
[
'foo' => 'big'
],
[
'bar' => 'fat'
],
[
'baz' => 'mamma'
]
]
];
$merged[0] = array_reduce($array[0], function($carry, $item) {
return array_merge((array) $carry, $item);
});
var_export($merged);
输出:
array (
0 =>
array (
'foo' => 'big',
'bar' => 'fat',
'baz' => 'mamma',
),
)
答案 2 :(得分:1)
此单行代码足以执行此操作
$newArr = call_user_func_array('array_merge',$dataArr); ///where $dataArr is your array..
call_user_func_array将使用参数数组调用回调函数,array_merge将在单个数组中合并所有这些参数阅读更多关于call_user_func_array()和array_merge()
的信息示例代码:
<?php
$dataArr = array(
array(
'Floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$newArr = call_user_func_array('array_merge',$dataArr);
echo "<pre>"; print_r($newArr);
?>
这会给你:
Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)