数组看起来像:

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

我有一个整数变量$v。

我如何选择一个数组条目,其中有一个对象的ID属性有$v值?


当前回答

您可以迭代数组,搜索特定的记录(只在一次搜索中),或者使用另一个关联数组构建hashmap。

对于前者,是这样的

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

有关后者的更多信息,请参阅此问题和后续答案-通过多个索引引用PHP数组

其他回答

我有时喜欢使用array_reduce()函数来执行搜索。它类似于array_filter(),但不会影响所搜索的数组,允许您对同一对象数组执行多次搜索。

$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find

//carry out the search
$search_results_array = array_reduce(
  $haystack,

  function($result_array, $current_item) use ($needle){
      //Found the an object that meets criteria? Add it to the the result array 
      if ($current_item->someProperty == $needle){
          $result_array[] = $current_item;
      }
      return $result_array;
  },
  array() //initially the array is empty (i.e.: item not found)
);

//report whether objects found
if (count($search_results_array) > 0){
  echo "found object(s): ";
  print_r($search_results_array[0]); //sample object found
} else {
  echo "did not find object(s): ";
}

我在这里找到了更好的解决方案。对这个问题的修改是这样的:

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);

您可以迭代数组,搜索特定的记录(只在一次搜索中),或者使用另一个关联数组构建hashmap。

对于前者,是这样的

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

有关后者的更多信息,请参阅此问题和后续答案-通过多个索引引用PHP数组

修复了@YurkaTim的一个小错误,你的解决方案为我工作,但增加了使用:

要在函数内部使用$searchedValue,可以在函数参数function ($e)后面使用($searchedValue)。

如果返回条件为真,array_filter函数只在$ needdobject时返回

如果$searchedValue是一个字符串或整数:

$searchedValue = 123456; // Value to search.
$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);
var_dump($neededObject); // To see the output

如果$searchedValue是一个数组,我们需要检查一个列表:

$searchedValue = array( 1, 5 ); // Value to search.
$neededObject  = array_filter(
    $arrayOfObjects,
    function ( $e ) use ( $searchedValue ) {
        return in_array( $e->term_id, $searchedValue );
    }
);
var_dump($neededObject); // To see the output

我解决了这个问题的关键数组与ID。对于ID就是您要查找的内容的这种情况,这种方法更简单,可能也更快。

[420] => stdClass Object
        (
            [name] => Mary
         )

[10957] => stdClass Object
        (
            [name] => Blah
         )
...

现在我可以直接寻址数组:

$array[$v]->name = ...

或者,如果我想验证一个ID的存在:

if (array_key_exists($v, $array)) { ...