如何搜索/索引stdClass对象的数组


How to search/index an array of stdClass Object

我在这里读了一些帖子,但我找不到我想要的东西。我有一个stdClass对象数组。每个元素都包含表单字段的数据

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

因此,现在我正试图创建一个具有特定顺序字段的表单,并在数组变量已经存在的地方编辑一些代码。称之为$fields。我需要索引到这个数组中,这样对于我感兴趣的字段,我就可以检索所有数据。例如,这相当于能够实现以下内容:将$fields的行作为$row,其中字段标题为title,这样我就可以访问作为$row->$id的数据,等等。

我知道这一定是初级的,但我的阵法技能很有限!谢谢

edit:啊,我刚刚发现了这个:PHP-从一个对象数组中按对象属性查找条目这似乎是我需要的。

使用array_filter获取所需字段:

// 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];