这是我的第一个数组,其中我有我想要的数组的id:
$needlearray = (0 => 12421, 1 => 58902, 2 => 912, 3 => 42);
然后第二个数组包含所有带有单词数据的单词:
$haystackarray = (
0 => array('id' => 42, 'word' => "hello", 'otherdata' => "other"),
1 => array('id' => 12421, 'word' => "good", 'otherdata' => "other"),
2 => array('id' => 58902, 'word' => "hello", 'otherdata' => "other"),
3 => array('id' => 5222, 'word' => "hello", 'otherdata' => "other"),
4 => array('id' => 912, 'word' => "hello", 'otherdata' => "other"),
5 => array('id' => 43290, 'word' => "hello", 'otherdata' => "other"),
6 => array('id' => 2312, 'word' => "hello", 'otherdata' => "other")
);
我希望以最快的方式输出,使用$needlearray
值从$haystackarray
查找“id”。例如我想要使用上面的例子的输出是:
$result = (
0 => array('id' => 12421, 'word' => "good", 'otherdata' => "other"),
1 => array('id' => 58902, 'word' => "hello", 'otherdata' => "other"),
2 => array('id' => 912, 'word' => "hello", 'otherdata' => "other"),
3 => array('id' => 42, 'word' => "hello", 'otherdata' => "other"),
);
注意:
foreach
循环。这很慢。$needlearray
的原始订单。$needlearray
中包含数千个值,在$haystackarray
中也包含数千个数组。答案 0 :(得分:0)
你真的想在数据库中这样做。你会做这样的事情:
$list = implode(',', $needlearray);
$query = "SELECT id, word, otherdata FROM table
WHERE id IN($list)
ORDER BY FIELD(id, $list)";
id
在列表中的行id
如果您需要在PHP中执行此操作,那么这可能会或可能不会比foreach()
更快:
$result = array_intersect_key(array_column($haystackarray, null, 'id'),
array_flip($needlearray));
id
订单将不会被维护,因此您需要按针对haystack进行排序,因此数据库是可行的方法。
答案 1 :(得分:0)
您可以使用array_intersect函数。
<?php
$needlearray = [0 => 12421, 1 => 58902, 2 => 912, 3 => 42];
$haystackarray = [
0 => array('id' => 42, 'word' => "hello", 'otherdata' => "other"),
1 => array('id' => 12421, 'word' => "good", 'otherdata' => "other"),
2 => array('id' => 58902, 'word' => "hello", 'otherdata' => "other"),
3 => array('id' => 5222, 'word' => "hello", 'otherdata' => "other"),
4 => array('id' => 912, 'word' => "hello", 'otherdata' => "other"),
5 => array('id' => 43290, 'word' => "hello", 'otherdata' => "other"),
6 => array('id' => 2312, 'word' => "hello", 'otherdata' => "other")
];
$result = array_intersect_key($haystackarray, array_intersect(array_column($haystackarray, 'id'), $needlearray));
echo "<pre>";
print_r($result);exit();