简体   繁体   English

计算不同类别ID的数量?

[英]Count the amount of different category id?

So I have the following array like this : 所以我有下面这样的数组:

[0] => Array
        (
            [id] => 10
            [rec_id] => 4
            [mid] => a:2:{i:0;s:1:"2";i:1;s:1:"5";}
            [cid] => 5
            [lang] => geo
            [title] => ჯიმი მორისონი გაცოცხლდა
            [intro] =>
            [img] => xhdvlmvogeujm76.jpg
        [text] =>

        )

    [1] => Array
        (

            [id] => 7
            [rec_id] => 6
            [mid] => a:2:{i:0;s:1:"2";i:1;s:1:"5";}
            [cid] => 3
            [lang] => geo
            [title] => 70 people died
            [intro] =>
            [img] => as554ghbvwe5.jpg
        [text] =>

        )




)

What I want to do is count how many different Cid (category id) are in my items. 我想做的是计算项目中有多少个不同的Cid(类别ID)。 Let's say I have 5 items with each a different cid, then counter should return 5, if 3 out of these 5 have the same cid, then it returns 3 and so on. 假设我有5个项目,每个项目都有不同的cid,然后计数器应返回5,如果这5个项目中有3个具有相同的cid,则它返回3,依此类推。 I've been tempering with foreach() but no luck . 我一直在尝试foreach()但是没有运气。 here what i tried 这是我尝试过的

foreach ($data as $k=>$v)
{
    if ($v['cid']!=$v['cid']){
        $counter=$counter+1;
    }
}

If you're using PHP 5.5+ you can use 如果您使用的是PHP 5.5+,则可以使用

$uniqueCids = array_unique(
    array_column(
        $myArray,
        'cid'
    )
);

For PHP < 5.5, you can use 对于PHP <5.5,可以使用

$uniqueCids = array_unique(
    array_map(
        function($value) {
            return $value['cid'];
        },
        $myArray
    )
);

Then just do 然后就做

$uniqueCidCount = count($uniqueCids);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM