0

I have read some posts on here but I can't quite find what I am looking for. I have an array of stdClass Objects. Each element contains data for a field for a form. So you can imagine something like

Array ( [0] => stdClass Object ( [id] => 1 [title] => title ...

So now I am trying to create a form with fields in a certain order and am editing some code where the array variable already exists. Call it $fields. I need to index into this array so for the field I am interested in, I can retrieve all the data. This amounts to being able to, for instance, achieve the following: get me the row of $fields as $row where the field title is title so that I can then access the data as $row->$id, etc.

I know this must be elementary, but my array skills are quite limited! Thanks!

edit: Ahhh, I just found this: PHP - find entry by object property from a array of objects That seems to be what I need.

Community
  • 1
  • 1
Brian
  • 125
  • 2
  • 15
  • possible duplicate of [PHP - find entry by object property from a array of objects](http://stackoverflow.com/questions/4742903/php-find-entry-by-object-property-from-a-array-of-objects) – georg Feb 09 '15 at 14:15

1 Answers1

1

Use array_filter to get the field you need:

// this is the key you are looking for
$keyToLookFor = 'title';

// filter takes two arguments, the original array and a callback function, which returns true or false based on the desired logic
$foundField = array_filter($originalArray, function($field) use($keyToLookFor){
  return $field -> title === $keyToLookFor;
});

// as array_filter returns an array of results, you just want the first element of such array:
$foundField = $foundField[0];
moonwave99
  • 21,957
  • 3
  • 43
  • 64