【问题标题】:How to search/index an array of stdClass Object如何搜索/索引 stdClass 对象数组
【发布时间】:2015-02-09 13:34:08
【问题描述】:

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

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

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

我知道这一定是初级的,但是我的阵法非常有限!谢谢!

编辑:啊,我刚刚找到了这个:PHP - find entry by object property from a array of objects 这似乎是我需要的。

【问题讨论】:

标签: php arrays


【解决方案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];

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2016-05-23
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多