Array([130] => Array
(
[0] => Array
(
[first_name] => John
[last_name] => Smith
)
[1] => Array
(
[first_name] => Jane
[last_name] => Doe
)
[123] => Array
(
[0] => Array
(
[first_name] => Ann
[last_name] => Green
)
[1] => Array
(
[first_name] => Thor
[last_name] => Grey
)
)
如何制作像这样的数组
Array(
[130] => Array
(
[first_name] => "John, Jane"
[123] => Array
(
[first_name] => "Ann, Thor"
)
答案 0 :(得分:0)
以下是使用foreach()
和variable by reference的快速简单解决方案:
foreach($your_array as &$current) {
$current = array(
'first_name' => $current[0]['first_name'] . ', ' . $current[1]['first_name']
);
}
但假设您的子阵列中可能有多个人而不是两个人,这是一个更好的解决方案:
foreach($your_array as &$current) {
$to_append = array(); // use a temporary array
foreach($current as $sub_array) {
$to_append[] = $sub_array['first_name']; // add each first name to temp
}
// overwrite current main array iteration with imploded temporary array
$current = array('first_name' => implode(', ', $to_append));
}
-
以下是另一种不使用foreach()
的解决方案,而是通过引用将array_walk()
和array_map()
与变量结合使用:
array_walk($your_array, function(&$array_branch) {
$names = array_map(function($a){
return $a['first_name']; // return all the first names
}, $array_branch);
// combine the first names together
$array_branch = array('first_name' => implode(', ', $names));
});
$array_branch
表示主阵列中的每个数组(键130和123)并通过引用传递,因此每次都会覆盖其值