例如,我有$ dates1和$ dates2,如下所示,并且想要创建$ dates3,它将所有日期保存在$ dates1中,并在$ dates2中添加任何唯一日期,忽略任何重复日期。数组包含其他值,但我只是显示日期,因为这是我想要合并/排序的。
$ dates1 =
Array
(
[0] => Array
(
[day] => 2012-01-01
[foo] => "bar"
)
[1] => Array
(
[day] => 2012-01-02
[foo] => "bar"
)
[2] => Array
(
[day] => 2012-01-03
[foo] => "bar"
)
)
$ dates2 =
Array
(
[0] => Array
(
[day] => 2011-12-31
)
[1] => Array
(
[day] => 2012-01-01
)
[2] => Array
(
[day] => 2012-01-02
)
[3] => Array
(
[day] => 2012-01-03
)
[4] => Array
(
[day] => 2012-01-04
)
)
所以我想将$ dates2合并到$ dates1中,忽略任何重复项,以使$ date3:
Array
(
[0] => Array
(
[day] => 2011-12-31
)
[1] => Array
(
[day] => 2012-01-01
[foo] => "bar"
)
[2] => Array
(
[day] => 2012-01-02
[foo] => "bar"
)
[3] => Array
(
[day] => 2012-01-03
[foo] => "bar"
)
[4] => Array
(
[day] => 2012-01-04
)
)
答案 0 :(得分:0)
我不确定我是否理解你,你的意思是这样吗?
$old_array = array_merge($dates1, $dates2);
$new_array = array();
foreach ($old_array as $item){
if (!array_key_exists($item['day'], $new_array)){
$new_array[$item['day']] = $item;
}
}
return $new_array;
答案 1 :(得分:0)
这样的事情应该有效
$a1 = array(array('day' => '2012-01-01', 'foo' => 'bar1'),
array('day' => '2012-01-02', 'foo' => 'bar2'),
array('day' => '2012-01-03', 'foo' => 'bar3'));
$a2 = array(array('day' => '2011-12-31'),
array('day' => '2012-01-01'),
array('day' => '2012-01-02'),
array('day' => '2012-01-03'),
array('day' => '2012-01-04'));
$orderedArray = array();
foreach (array_merge($a1, $a2) as $v)
{
if (count($v) == 1 && isset($orderedArray[$v['day']]))
continue;
$orderedArray[$v['day']] = $v;
}
ksort($orderedArray);
print_r($orderedArray);
编辑:我重构了代码。