我试图找出比较两个不同对象数组的最佳方法。两个阵列的结构相同。 e.g:
Array
(
[0] => stdClass Object
(
[f_name] => Luis
[id] => 1
[rank] => 1
)
[1] => stdClass Object
(
[f_name] => Eden
[id] => 2
[rank] => 2
)
[2] => stdClass Object
(
[f_name] => Robin
[id] => 4
[rank] => 3
)
[3] => stdClass Object
(
[f_name] => Wayne
[id] => 3
[rank] => 4
)
)
第一个数组中有大约600个对象,第二个数组中有一个变量数。我不想循环遍历较小的数组并取消设置较大数组的任何匹配,但这是我能想到的唯一方法。还有更好的方法吗?
当我从数据库(mySQL)中提取这个时,会有更好的方法吗?我意识到这是一个单独的问题,如果普遍的共识是在那里做,我会相应地问它。
修改
在回复评论时,查询非常笨拙,我简化了返回的对象,但这是它的要点:
查询1(更大的结果集)
SELECT `players`.`f_name`, `players`.`id`, `default_rankings`.`rank` FROM `default_rankings`
LEFT JOIN `players` ON `players`.`id` = `default_rankings`.`player_id`
ORDER BY `default_rankings`.`rank` asc
查询2(较小的结果集)
SELECT `players`.`f_name`, `players`.`id`, `player_rankings`.`rank` FROM `player_rankings`
LEFT JOIN `players` ON `players`.`id` = `player_rankings`.`player_id`
WHERE `player_rankings`.`user_id` = '1'
ORDER BY `player_rankings`.`rank` asc
修改
继来自@ MarcB的评论之后,我将我的第一个查询改为:
SELECT `players`.`f_name`, `players`.`id`, `default_rankings`.`rank` FROM `default_rankings`
LEFT JOIN `players` ON `players`.`id` = `default_rankings`.`player_id`
WHERE `players`.`id` NOT IN (SELECT `player_id` FROM `user_rankings` WHERE `user_id` = '1')
ORDER BY `default_rankings`.`rank` asc
哪个效果很好,因为它一旦交给前端控制器就没有任何限制和抵消。
答案 0 :(得分:0)
我认为array_intersect()将是最佳选择。 http://www.php.net/manual/en/function.array-intersect.php -
PHP文档示例 -
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
// output
Array
(
[a] => green
[0] => red
)