使用另一个数组中的值从数组中查找值

时间:2016-06-07 15:15:42

标签: php arrays

这是我的第一个数组,其中我有我想要的数组的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中也包含数千个数组。
  • 速度非常重要,因为这是大型过程的一部分。

2 个答案:

答案 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
  • 翻转针以获取索引值
  • 找到交叉点(公共密钥)

订单将不会被维护,因此您需要按针对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();

WORKING DEMO