How to find the index of an object where the key is a specific value?

I hope I say that correctly ...

How do I find the index where ID = 68?

I need help creating a function that returns index 2 ... Thanks!

$posts = Array ( [0] => stdClass Object ( [ID] => 20 [post_author] => 1 [post_content] => [post_title] => Carol Anshaw ) [1] => stdClass Object ( [ID] => 21 [post_author] => 1 [post_content] => [post_title] => Marie Arana ) [2] => stdClass Object ( [ID] => 68 [post_author] => 1 [post_content] => [post_title] => TC Boyle ) [3] => stdClass Object ( [ID] => 1395 [post_author] => 1 [post_content] => [post_title] => Rosellen Brown ) ) 
+4
source share
2 answers
  • Make a trivial function that iterates over an array

  • Encapsulate it instead of leaving it hanging

  • Remember to use var_export rather than print_r when inserting community data structures

You can make such a trivial function:

 function getKeyForId($id, $haystack) { foreach($haystack as $key => $value) { if ($value->ID == $id) { return $key; } } } $keyFor68 = getKeyForId(68, $posts); 

But it makes no sense to leave certain functions hanging. You can use ArrayObject as such:

 class Posts extends ArrayObject { public function getKeyForId($id) { foreach($this as $key => $value) { if ($value->ID == $id) { return $key; } } } } 

Usage example:

 $posts = new Posts(); $posts[] = new StdClass(); $posts[0]->ID = 1; $posts[0]->post_title = 'foo'; $posts[] = new StdClass(); $posts[1]->ID = 68; $posts[1]->post_title = 'bar'; $posts[] = new StdClass(); $posts[2]->ID = 123; $posts[2]->post_title = 'test'; echo "key for post 68: "; echo $posts->getKeyForId(68); echo "\n"; var_export($posts[$posts->getKeyForId(68)]); 

Conclusion:

 key for post 68: 1 stdClass::__set_state(array( 'ID' => 68, 'post_title' => 'bar', )) 
+4
source
 function findIndexById($id, $array) { foreach($array as $key => $value) { if($value->ID == $id) { return $key; } } return false; } 

and you can search for it like this findIndexById(68, $array); , this will return you the index of the array if it finds false otherwise.

0
source

Source: https://habr.com/ru/post/1412923/


All Articles