2015-02-09 113 views
0

我已經閱讀了這裏的一些帖子,但我無法完全找到我在找什麼。我有一個stdClass對象的數組。每個元素都包含表單字段的數據。所以你可以想象像如何搜索/索引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這似乎是我需要的。

+0

[PHP - 找到對象的數組通過對象屬性條目]的可能重複(http://stackoverflow.com/questions/4742903/php -find進入逐個對象屬性從 - 陣列對的一對象) – georg 2015-02-09 14:15:34

回答

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