假设我有几个具有相同结构的多维数组:
Array ( [0] => Tips Object ( [id] => 1 [userId] => 10 )
[1] => Tips Object ( [id] => 2 [userId] => 22 )
[2] => Tips Object ( [id] => 3 [userId] => 33 )
[3] => Tips Object ( [id] => 7 [userId] => 77 ) )
Array ( [0] => Tips Object ( [id] => 2 [userId] => 22 )
[1] => Tips Object ( [id] => 3 [userId] => 33 )
[2] => Tips Object ( [id] => 4 [userId] => 44 )
[3] => Tips Object ( [id] => 5 [userId] => 55 )
[4] => Tips Object ( [id] => 6 [userId] => 66 ) )
我需要一种方法来合并它们,所以我会得到这个:
Array ( [0] => Tips Object ( [id] => 1 [userId] => 10 )
[1] => Tips Object ( [id] => 2 [userId] => 22 )
[2] => Tips Object ( [id] => 3 [userId] => 33 )
[3] => Tips Object ( [id] => 4 [userId] => 44 )
[4] => Tips Object ( [id] => 5 [userId] => 55 )
[5] => Tips Object ( [id] => 6 [userId] => 66 )
[6] => Tips Object ( [id] => 7 [userId] => 77 ) )
真正的多维数组将更复杂,这只是为了帮助解释我需要的东西。
感谢!!!!
答案 0 :(得分:0)
我假设你要做的是将两个排序的序列(通过id或userid)合并到最终的排序序列中。在这种情况下,请查看MergeSort中使用的合并过程:http://en.wikipedia.org/wiki/Merge_sort#Algorithm
答案 1 :(得分:0)
$array1=array( 0=>array('id'=>'1','userid'=>'10'),
1=>array('id'=>'2','userid'=>'22'),
2=>array('id'=>'3','userid'=>'33'),
3=>array('id'=>'7','userid'=>'77'));
$array2=array( 0=>array('id'=>'2','userid'=>'22'),
1=>array('id'=>'3','userid'=>'33'),
2=>array('id'=>'4','userid'=>'44'),
3=>array('id'=>'5','userid'=>'55'),
4=>array('id'=>'6','userid'=>'66'));
echo "<pre>";
$mix = array();
foreach($array2 as $k=>$value)
{
if(!in_array($value,array_values($array1))){
$array1[] = $value;
}
}
function sortById($a, $b) {
return $a['id'] - $b['id'];
}
usort($array1, 'sortById');
print_r($array1);
exit;