doushang1880 2014-09-03 00:43
浏览 29
已采纳

根据深度数组中任何位置存在的特定键创建唯一值列表

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.

Example

Suppose the array is:

$bigArray = array(
    'name'=>'one', 
    'something'=>array(
        'name'=>'two', 
        'subthing'=>array('name'=>'three')
    ), 
    'anotherthing'=>array('name'=>'one')
);

The expected result would be:

$uniques = array('one', 'two', 'three') // All the 'name' keys values and without duplicates.

Here's a fiddle of my attempt.

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.

  • 写回答

3条回答 默认 最新

  • dongruidian3064 2014-09-03 00:48
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算