我有这两个数组:
$list = [
'fruit' => [],
'animals' => [],
'objects' => [],
];
$dataArray = [
'fruit' => 'apple',
'animals' => ['dog', 'cat'],
'asd' => 'bla'
];
我希望将它们合并,以便最终的 $list 为:
[fruit] => Array
(
[0] => apple
)
[animals] => Array
(
[0] => dog
[1] => cat
)
[objects] => Array
(
)
需要注意的事项:
- 即使'fruit'只有一个元素,在$list中仍然是一个数组。
- $list中缺少的键(如'asd'键)将被简单地忽略。
- 即使为空,键也将保留,不会被删除。
使用array_merge无法实现:
$merged = array_merge($list, $dataArray);
[fruit] => apple
[animals] => Array
(
[0] => dog
[1] => cat
)
[objects] => Array
(
)
[asd] => bla
我用以下方法成功地得到了我想要的内容:
foreach ($dataArray as $key => $value) {
if (isset($list[$key])) {
if (is_array($value)) {
$list[$key] = $value;
}
else {
$list[$key] = [$value];
}
}
}
但是我在想是否有更简洁的方法或者其他我不知道的php函数。
array_walk()
函数,您可以将循环包装在一个函数中,并且它将完成所有的工作,但是不存在内置函数可以满足您想要的所有需求。 - Thielicious