我在PHP中有這個簡單的數組$tree
,我需要根據與數組中的數組匹配的標籤進行過濾。匿名PHP函數in_array無法正常工作
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
我試圖用一個匿名函數,像這樣:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return in_array($array->tags, $selectedTags, true);
});
$ selectedTags:
Array
(
[0] => client corp
)
以上是返回的空當,我期望要返回第1項。沒有錯誤拋出。我錯過了什麼?
對不起,目前的行爲有點不清楚。它不工作?它沒有正確過濾嗎?它拋出異常嗎? – 2014-11-20 23:01:25
@ChrisForrence對不起,它不是過濾(即返回空)。沒有錯誤拋出。 – greener 2014-11-20 23:02:08
你的函數在'$ array-> tags'中搜索'$ selectedTags',它們都是數組。 'in_array()'只會在數組完全匹配時才返回true(相同數量的元素具有相同的內容)。您需要遍歷一個數組,依次搜索另一個數組中的每個元素。 – 2014-11-20 23:04:58