dongyou8368 2015-11-06 17:10
浏览 40
已采纳

如何计算关联/嵌套数组的叶元素

I have been trying to count the last leaf node elements in a array. Im thinking along the lines of:

  • Getting a simple array of leaf elements from the testArray using: 'array_walk_recursive'.
  • Count elements in the new array using: 'array_count_values'.

Im unsure how to get a simple list array from 'array_walk_recursive', i just get a long string of values....or is there a better way of achieving this result?

DESIRED RESULT:

flammable = 1
irritant = 2 
toxic = 3

PHP:

$testArray = Array
(
    [0] => Array
    (
        [0] => toxic
        [1] => irritant
        [3] => flammable
    )

    [1] => Array
    (
        [0] => toxic
        [1] => irritant
    )

    [2] => Array
    (
        [0] => toxic
    )
);

array_walk_recursive($testArray, function(&$value) 
{
    echo 'string = '.$value;
    print_r(newArray);              //How can i get this new array list?
});

 $counts = array_count_values($newArray); //and use this to count values?
  • 写回答

1条回答 默认 最新

  • dongxiaofa6359 2015-11-06 17:13
    关注

    Try this, the numbers should show up in the $groups array.

    $groups = array();
    
    array_walk_recursive($testArray, function(&$value) use (&$groups)
    {
        if (isset($groups[$value])) {
            $groups[$value]++;
        } else {
            $groups[$value] = 1;
        }
    });
    
    print_r($groups);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了