我有一個由未確定數量的數組遞歸(深度n級)組成的數組。每個陣列可能包含一個name
密鑰。我想創建這些值的唯一列表。從深度數組中的任意位置存在的特定鍵值中創建一個唯一值列表
例
假設陣列是:
$bigArray = array(
'name'=>'one',
'something'=>array(
'name'=>'two',
'subthing'=>array('name'=>'three')
),
'anotherthing'=>array('name'=>'one')
);
預期的結果將是:
$uniques = array('one', 'two', 'three') // All the 'name' keys values and without duplicates.
這裏的一個fiddle of my attempt。
我的方法是使用array_walk_recursive
傳遞$uniques
數組作爲參考,並允許函數來更新該值:
$uniques = array();
function singleOut($item, $key, &$uniques) {
if ($key == 'name' && !in_array($itm,$uniques,true))
$uniques[] = $item;
}
array_walk_recursive($bigArray, 'singleOut', $uniques);
然而,這不是爲我工作。
對於這個問題的範圍,一個鬆散的比較就好了。但是,當對可能爲_0的鍵進行鬆散比較時,請訪問此鏈接以查看潛在的意外結果(感謝PHP的類型雜耍)。 [類型雜耍,而鬆散比較產生不必要的結果](https://stackoverflow.com/questions/44426990/type-juggling-while-making-loose-comparison-yields-unwanted-result)] – mickmackusa 2017-09-08 02:23:14