想将数组转换成上面在PHP中给出的示例
我有这个数组
Array
(
[0] => Array
(
[101] => Abbottabad
)
[1] => Array
(
[102] => Abdul Hakim
)
[2] => Array
(
[103] => Ahmed Pur East
)
)
想要实现这一目标
Array
(
[101] => Abbottabad
[102] => Abdul Hakim
[103] => Ahmed Pur East
)
答案 0 :(得分:1)
您可以使用两个循环来迭代主数组,然后迭代子数组,以便在其中跟踪键和值。假设您的数组名称为$arr
:
$new_arr = array();
foreach($arr as $subarr) {
foreach($subarr as $key => $value) {
$new_arr[$key] = $value;
}
}
答案 1 :(得分:1)
如果您不喜欢循环外观:
$array = array(array(101=>'Abbottabad'),array(102=>'Abdul Hakim'),array(103=>'Ahmed Pur East'));
$merged_array = call_user_func_array('array_merge',$array);
print_r($merged_array);
/* Result
Array
(
[0] => Abbottabad
[1] => Abdul Hakim
[2] => Ahmed Pur East
)
*/
答案 2 :(得分:1)
由于示例数据每个数组仅包含一个项目,因此您可以使用key并在foreach循环内重置。
例如:
$arrays = [
[101 => "Abbottabad"],
[102 => "Abdul Hakim"],
[103 => "Ahmed Pur East"]
];
$res = [];
foreach($arrays as $array) {
$res[key($array)] = reset($array);
}
print_r($res);
结果
Array
(
[101] => Abbottabad
[102] => Abdul Hakim
[103] => Ahmed Pur East
)
注意:阵列键必须唯一。