根据深层阵列中任何地方存在的特定键制作唯一的值列表 [英] Make a unique list of values from a particular key existing anywhere in a deep array

查看:97
本文介绍了根据深层阵列中任何地方存在的特定键制作唯一的值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,该数组递归地(n层深)由不确定数量的数组组成.每个数组可能包含一个name键.我想为这些值创建一个唯一列表.

I have an array that consists of an undetermined number of arrays, recursively (n levels deep). Each array might contain a name key. I want to create a unique list of those values.

示例

假设数组为:

$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.

这是一个我的尝试很简单.

我的方法是使用array_walk_recursive传递$uniques数组作为参考,并允许函数更新该值:

My approach was using array_walk_recursive passing a $uniques array as reference, and allowing the function to update that value:

$uniques = array();

function singleOut($item, $key, &$uniques) {
    if ($key == 'name' && !in_array($itm,$uniques,true) )
        $uniques[] = $item;
}

array_walk_recursive($bigArray, 'singleOut', $uniques);

但是,它对我不起作用.

However, it's not working for me.

推荐答案

您也可以在此计算机上使用array_unique.示例:

You could use also array_unique on this one too. Example:

$uniques = array();
array_walk_recursive($bigArray, function($val, $key) use (&$uniques){
    if($key == 'name') {
        $uniques[] = $val;
    }
});

$uniques = array_unique($uniques); // unique values

这篇关于根据深层阵列中任何地方存在的特定键制作唯一的值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆