PHP -从对象数组中按对象属性查找条目

时间:2021-01-09 21:19:03

The array looks like:

数组的样子:

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

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

And I have a integer variable called $v.

我有一个整数变量$v。

How could I select a array entry that has a object where the 'ID' property has the $v value ?

我如何选择一个具有“ID”属性为$v值的对象的数组项?

9 个解决方案

#1


133  

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

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

For the former, something like this

对于前者,就像这样

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

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes

有关后一个引用PHP数组的更多信息,请参见这个问题和后面的答案

#2


50  

YurkamTim is right. It needs only a modification: (Sorry I can't comment now).

YurkamTim是正确的。它只需要修改一下:(对不起,我现在不能评论)。

After function($) you need a pointer to the external variable by "use(&$searchedValue)" and then you can access the external variable. Also you can modify it.

函数($)之后,需要通过“use(&$searchedValue)”指向外部变量的指针,然后才能访问外部变量。你也可以修改它。

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

#3


18  

I've found more elegant solution here. Adapted to the question it may look like:

我在这里找到了更优雅的解决方案。适应了以下问题:

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

#4


6  

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using the way you wanted would be something like:

用你想要的方式是:

ArrayUtils::objArraySearch($array,'ID',$v);

#5


4  

Using array_column to re-index will save time if you need to find multiple times:

如果需要多次查找,使用array_column重新索引可以节省时间:

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

Then you can simply $lookup[$id] at will.

然后您可以随意地查找$ [$id]。

#6


2  

I sometimes like using the array_reduce() function to carry out the search. It's similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

我有时喜欢使用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): ";
}

#7


2  

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

#8


2  

Fixing a small mistake of the @YurkaTim, your solution work for me but adding use:

修复@YurkaTim的一个小错误,您的解决方案对我来说是可行的,但是增加了用途:

To use $searchedValue, inside of the function, one solution can be use ($searchedValue) after function parameters function ($e) HERE.

要使用$searchedValue,在函数内部,可以在函数参数函数($e)之后使用一个解决方案($searchedValue)。

the array_filter function only return on $neededObject the if the condition on return is true

array_filter函数只返回$neededObject中的if条件为true

If $searchedValue is a string or integer:

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

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

If $searchedValue is array where we need check with a list:

如果$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($searchedValue); // To see the output

#9


1  

I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.

我使用了某种Java keymap。如果这样做,就不需要每次都对对象数组进行循环。

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

输出:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk

#1


133  

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

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

For the former, something like this

对于前者,就像这样

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

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes

有关后一个引用PHP数组的更多信息,请参见这个问题和后面的答案

#2


50  

YurkamTim is right. It needs only a modification: (Sorry I can't comment now).

YurkamTim是正确的。它只需要修改一下:(对不起,我现在不能评论)。

After function($) you need a pointer to the external variable by "use(&$searchedValue)" and then you can access the external variable. Also you can modify it.

函数($)之后,需要通过“use(&$searchedValue)”指向外部变量的指针,然后才能访问外部变量。你也可以修改它。

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

#3


18  

I've found more elegant solution here. Adapted to the question it may look like:

我在这里找到了更优雅的解决方案。适应了以下问题:

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

#4


6  

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using the way you wanted would be something like:

用你想要的方式是:

ArrayUtils::objArraySearch($array,'ID',$v);

#5


4  

Using array_column to re-index will save time if you need to find multiple times:

如果需要多次查找,使用array_column重新索引可以节省时间:

$lookup = array_column($arr, NULL, 'id');   // re-index by 'id'

Then you can simply $lookup[$id] at will.

然后您可以随意地查找$ [$id]。

#6


2  

I sometimes like using the array_reduce() function to carry out the search. It's similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

我有时喜欢使用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): ";
}

#7


2  

$arr = [
  [
    'ID' => 1
  ]
];

echo array_search(1, array_column($arr, 'ID')); // prints 0 (!== false)

#8


2  

Fixing a small mistake of the @YurkaTim, your solution work for me but adding use:

修复@YurkaTim的一个小错误,您的解决方案对我来说是可行的,但是增加了用途:

To use $searchedValue, inside of the function, one solution can be use ($searchedValue) after function parameters function ($e) HERE.

要使用$searchedValue,在函数内部,可以在函数参数函数($e)之后使用一个解决方案($searchedValue)。

the array_filter function only return on $neededObject the if the condition on return is true

array_filter函数只返回$neededObject中的if条件为true

If $searchedValue is a string or integer:

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

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

If $searchedValue is array where we need check with a list:

如果$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($searchedValue); // To see the output

#9


1  

I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.

我使用了某种Java keymap。如果这样做,就不需要每次都对对象数组进行循环。

<?php

//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);

//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
    //fill second        key          value
    $secondArray[$value->id] = $value->name;
}

var_dump($secondArray);

echo $secondArray['123'];

output:

输出:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'id' => int 123
      public 'name' => string 'Henk' (length=4)
      public 'age' => int 65
  1 => 
    object(stdClass)[2]
      public 'id' => int 273
      public 'name' => string 'Koos' (length=4)
      public 'age' => int 25
array (size=2)
  123 => string 'Henk' (length=4)
  273 => string 'Koos' (length=4)
Henk