skip to Main Content

I have an Array like below, is there any way to count the total number of occurrences of CID.
For example:

CID = 992010000021102

I want to count the result as 2

– Laravel 6, php 7.4

{
    "status": true,
    "message": null,
    "data": [
        [
            {
                "cid": "99201000021102",
                "mailaddress": "[email protected]"
            },
            {
                "cid": "99201000021105",
                "mailaddress": "[email protected]"
            }
        ],
        [
            {
                "cid": "00003900062153",
                "mailaddress": "[email protected]"
            }
        ],
        [
            {
                "cid": "99201000021102",
                "mailaddress": "[email protected]"
            }
        ],
        [
            {
                "cid": "99201000021101",
                "mailaddress": "[email protected]"
            }
        ]
    ]
}

I tried running the loops but the result is not as expected.

5

Answers


  1. To count the total number of occurrences of a specific value in an array, you can use a loop to iterate through the array and increment a counter variable each time the value is found. For example in your case..

    $array = [
        [
            [
                "cid" => "99201000021102",
                "mailaddress" => "[email protected]"
            ],
            [
                "cid" => "99201000021105",
                "mailaddress" => "[email protected]"
            ]
        ],
        [
            [
                "cid" => "00003900062153",
                "mailaddress" => "[email protected]"
            ]
        ],
        [
            [
                "cid" => "99201000021102",
                "mailaddress" => "[email protected]"
            ]
        ],
        [
            [
                "cid" => "99201000021101",
                "mailaddress" => "[email protected]"
            ]
        ]
    ];
    
    $cid = "99201000021102";
    $count = 0;
    
    foreach ($array as $item) {
        foreach ($item as $innerItem) {
            if ($innerItem['cid'] == $cid) {
                $count++;
            }
        }
    }
    
    echo $count; // Outputs 2
    
    Login or Signup to reply.
  2. You can try this:

    $countArr = [];
    foreach ($arr as $val){
        foreach ($val as $value){
            if (!array_key_exists($value['cid'], $countArr)){
                $countArr[$value['cid']] = 1;
            }else $countArr[$value['cid']] += 1;
        }
    }
    print_r($countArr);
    

    It will print:

    Array
    (
        [99201000021102] => 2
        [99201000021105] => 1
        [00003900062153] => 1
        [99201000021101] => 1
    )
    

    Because in each array in the main array we have some objects, we need the nested loop. Each time we check if that CID exist in the final array if yes, we sum the occurrence with 1 otherwise we will push new CID with the occurrence of 1.

    Login or Signup to reply.
  3. You can get your result in jQuery also,
    Try this.

    var json = {
        "status": true,
        "message": null,
        "data": [
            [
                {
                    "cid": "99201000021102",
                    "mailaddress": "[email protected]"
                },
                {
                    "cid": "99201000021105",
                    "mailaddress": "[email protected]"
                }
            ],
            [
                {
                    "cid": "00003900062153",
                    "mailaddress": "[email protected]"
                }
            ],
            [
                {
                    "cid": "99201000021102",
                    "mailaddress": "[email protected]"
                }
            ],
            [
                {
                    "cid": "99201000021101",
                    "mailaddress": "[email protected]"
                }
            ]
        ]
    };
    var testOp = getKeys(json,"99201000021102");
    alert('Serach result found no of time : '+testOp);
    function getKeys(obj, val) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i)) continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getKeys(obj[i], val));
            } else if (obj[i] == val) {
                objects.push(i);
            }
        }
        return objects.length;
    }
    Login or Signup to reply.
    • You can use collection helpers of Laravel on your data array, pretty simple

    • Convert you data array to collection and flatten 1 level and groupBy "cid" column

      $collectionResult = collect($data)->flatten(1)->groupBy(‘cid’);

    • $data variable is data array get from your response, and flatten need to be done as per your data set from your data we need to apply only one level flatten to get data as stream to group By properly.

    • Print output result, you will get your expected results.

    Login or Signup to reply.
  4. A simple solution using array_filter:

    $count = count(
        array_filter(
            $yourarray->data,
            function($v) {
                return $v[0]->cid === '99201000021102';
            }
        )
    );
    

    Explanation:

    • $v[0]->cid is compared against the value we search for the value
    • we have a function that’s passed as the second parameter to array_filter which will determine which items would end up in the result, while $yourarray->data is passed as the first parameter
    • the result of array_filter is an array that contains the items for which the function was true and nothing else
    • using count we get the number of elements in the filtered array

    Additionally, if you do not know the value to search for in advance, use the use specification, like

    $a = '99201000021102';
    $count = count(
        array_filter(
            $yourarray->data,
            function($v) use ($a) {
                return $v[0]->cid === $a;
            }
        )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search