我正在尝试合并这两个数组
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
变成看起来像这样的数组
$arr1 = array(
'a' => array("1", "9"),
'b' => array("2", "8"),
'c' => array("3", ""),
'd' => array("", "7")
);
棘手的部分是空白.我需要将它们保留在原位.
谢谢
解决方法:
这是我的建议.根据您的描述,它将组合任意数量的数组.
error_reporting(E_ALL | E_STRICT);
header('Content-Type: text/plain');
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
$arr = combine($arr1, $arr2);
print_r($arr);
function combine() {
$keys = array();
foreach (func_get_args() as $arr) {
if (is_array($arr)) {
$keys += $arr;
}
}
$keys = array_keys($keys);
$values = array_pad(array(), count($keys), array());
$ret = array_combine($keys, $values);
foreach (func_get_args() as $arr) {
foreach ($keys as $k) {
$v = array_key_exists($k, $arr) ? $arr[$k] : '';
array_push($ret[$k], $v);
}
}
return $ret;
}
输出:
Array
(
[a] => Array
(
[0] => 1
[1] => 9
)
[b] => Array
(
[0] => 2
[1] => 8
)
[c] => Array
(
[0] => 3
[1] =>
)
[d] => Array
(
[0] =>
[1] => 7
)
)