dongxuanyi3406 2010-04-18 16:33
浏览 10
已采纳

PHP - 计算数组中的匹配数组

I have an array structure that looks like this:

    Array
(
    [0] => Array
        (
            [type] => image
            [data] => Array
                (
                    [id] => 1
                    [alias] => test
                    [caption] => no caption
                    [width] => 200
                    [height] => 200
                )

        )

    [1] => Array
        (
            [type] => image
            [data] => Array
                (
                    [id] => 2
                    [alias] => test2
                    [caption] => hello there
                    [width] => 150
                    [height] => 150
                )

        )

)

My question is, how can I get a count of the number of embedded arrays that have their type set as image (or anything else for that matter)? In practise this value can vary.

So, the above array would give me an answer of 2.

Thanks

  • 写回答

5条回答 默认 最新

  • duanlujiaji10335 2010-04-18 16:37
    关注

    The simplest way would simply be to loop over all the child arrays and check their type, incrementing a counter if it matches the required type.

    $count = 0;
    foreach ( $myarray as $child ){
        if ( $child['type'] == 'image' ){
            $count++;
        }
    }
    

    If you have PHP 5.3.0 or better you could use array_reduce (untested):

    $count = array_reduce($myarray, 
                          function($c, $a){ return $c + (int)($a['type'] == 'image'); },
                          0
             );
    

    Both of these could be moved into a function returning $count which would allow you to specify the type to count. For example:

    function countTypes(array $haystack, $type){
        $count = 0;
        foreach ( $haystack as $child ){
            if ( $child['type'] == $type ){
                $count++;
            }
        }
        return $count;
    }
    

    As you can see from other answers there is far more error checking you could do, however you as you haven't said what should be impossible (which you would want to use assert for).

    The possible errors are:

    • The child is not an array
    • The child does have the type key set

    If your array should always be set out like your example, failing silently (by putting a check in an if statement) would be a bad idea as it would mask an error in the program elsewhere.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错