在PHP中搜索多维数组并返回指针及其位置的最有效方法


Most efficient way to search a multidimensional array and return a needle and its position in PHP?

取这个简单的多维数组:

$images Array (
  [0] => Array (
    [image_id] => 18
    [votes] => 12
  )
  [1] => Array (
    [image_id] => 76
    [votes] => 10
  )
  ...
  [n] => Array (
    [image_id] => 2
    [votes] => 1
  )
)

在整个数组中搜索某个image_id值,然后返回该image_id在较大数组中的位置,同时返回相应的votes的最佳方法是什么?array_search()的某些变体是否能够管理此问题?

目前,我正在使用foreach循环:

foreach ($images as $image) {
  $i = 0;
  if ($image['image_id'] == $someNeedle) {
    $resultSet['image'] = $image;
    $resultSet['position'] = $i;
    return $resultSet;
  }
  $i++;
}

然而,这似乎过于复杂。有没有一个原生的PHP函数可以加快速度/使我的代码更具语义?谢谢

我怀疑您是否会找到另一种更快或更清晰的方法。

foreach ($images as $position => $image) {
  if ($image['image_id'] === $someNeedle) {
    return compact('image', 'position');
  }
}

http://php.net/manual/en/function.compact.php

没有一种内置的方法可以准确地返回您想要的内容。你可以稍微简化一下,但不需要太多:

foreach ($images as $key => $image) {
    if ($image['image_id'] == $someNeedle) {
        return array(
            'image' => $image,
            'position' => $key,
        );
    }
}

使用数组的key而不是i,它会给你位置,它可以更快一点:

foreach ($images as $key=>$image) {
  if ($image['image_id'] == $someNeedle) {
    $resultSet['image'] = $image;
    $resultSet['position'] = $key;
    return $resultSet;
  }
}
array_search($needle, array_column($array, 'column'));

感谢HCDINH的回答。