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

时间:2015-02-09 13:34:09

标签: php arrays

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

这样的东西
Array ( [0] => stdClass Object ( [id] => 1 [title] => title ...

所以现在我正在尝试按特定顺序创建一个包含字段的表单,并且正在编辑一些已存在数组变量的代码。称之为$fields。我需要索引到这个数组,所以对于我感兴趣的字段,我可以检索所有数据。例如,这相当于能够实现以下目标:将$fields$row作为title,其中字段标题为$row->$id,以便我可以将数据作为{{ {1}}等等。

我知道这必须是基本的,但我的阵列技能非常有限!谢谢!

编辑:啊,我刚刚发现:PHP - find entry by object property from a array of objects这似乎就是我的需要。

1 个答案:

答案 0 :(得分:1)

使用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];
相关问题