How to find entry by object property from an array of objects?

PhpArraysObject

Php Problem Overview


The array looks like:

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

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

And I have an integer variable called $v.

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

Php Solutions


Solution 1 - Php

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.

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 - https://stackoverflow.com/questions/4405281/reference-php-array-by-multiple-indexes

Solution 2 - Php

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

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

Above code echoes the index of the matching element, or false if none.

To get the corresponding element, do something like:

$i = array_search(1, array_column($arr, 'ID'));
$element = ($i !== false ? $arr[$i] : null);

array_column works both on an array of arrays, and on an array of objects.

Solution 3 - Php

YurkamTim is right. It needs only a modification:

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.

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

Solution 4 - Php

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

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

Solution 5 - Php

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

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

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

Solution 6 - Php

Try

$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));

working example here

Solution 7 - Php

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

Using it the way you wanted would be something like:

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

Solution 8 - Php

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

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

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

If $searchedValue is a string or integer:

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

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

$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

Solution 9 - Php

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.

$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): ";
}

Solution 10 - Php

Way to instantly get first value:

$neededObject = array_reduce(
    $arrayOfObjects,
    function ($result, $item) use ($searchedValue) {
        return $item->id == $searchedValue ? $item : $result;
    }
);

Solution 11 - Php

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.

<?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

Solution 12 - Php

I solved this problem by keying the array with the ID. It's simpler and possibly faster for this scenario where the ID is what you're looking for.

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

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

Now I can directly address the array:

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

Or, if I want to verify the existence of an ID:

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

Solution 13 - Php

I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: <https://stackoverflow.com/a/52786742/1678210>

I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.

Solution 14 - Php

      $keyToLookFor = $term->name;
      $foundField = array_filter($categories, function($field) use($keyToLookFor){
      return $field -> name === $keyToLookFor; });

      if(!empty($foundField)){
      $ke = array_keys($foundField);
      $ke = $ke[0];
      $v = $foundField[$ke]->id;}

Am Working On Wordpress Theme Get Total Comment from Catagories And This help me out for Arrays

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PhpPhilView Answer on Stackoverflow
Solution 2 - PhpTimView Answer on Stackoverflow
Solution 3 - PhpDaniel HardtView Answer on Stackoverflow
Solution 4 - PhpYurkaTimView Answer on Stackoverflow
Solution 5 - PhpMusefulView Answer on Stackoverflow
Solution 6 - PhpKamil KiełczewskiView Answer on Stackoverflow
Solution 7 - PhpPablo S G PachecoView Answer on Stackoverflow
Solution 8 - PhpJose Carlos Ramos CarmenatesView Answer on Stackoverflow
Solution 9 - PhpyuvilioView Answer on Stackoverflow
Solution 10 - PhpAndreyPView Answer on Stackoverflow
Solution 11 - PhpMart-JanView Answer on Stackoverflow
Solution 12 - PhpChad E.View Answer on Stackoverflow
Solution 13 - PhpJustin JackView Answer on Stackoverflow
Solution 14 - Phpamosu donaView Answer on Stackoverflow