0

I have an multidimensional array and I need to count their specific value

Array
(
 [0] => Array
    (
      [Report] => Array
        (
         [id] => 10
         [channel] => 1
         )
     )

    [1] => Array
      (
       [Report] => Array
         (
           [id] => 92
           [channel] => 0
         )
      )

    [2] => Array
      (
         [Report] => Array
         (
            [id] => 18
            [channel] => 0
         )
      )
    [n] => Array
)

I need to get output like that: channel_1 = 1; channel_0 = 2 etc

I made a function with foreach:

foreach ($array as $item) {
  echo $item['Report']['channel'];
} 

and I get: 1 0 0 ... but how can I count it like: channel_1 = 1; channel_0 = 2, channel_n = n etc?

2 Answers 2

1

Try this. See comments for step-by-step explanation. Outputs:

array(2) {
  ["channel_1"]=>
  int(1)
  ["channel_0"]=>
  int(2)
}

Code:

<?php

// Your input array.
$a =
[
    [
        'Report' =>
        [
            'id' => 10,
            'channel' => 1
        ]
    ],
    [
        'Report' =>
        [
            'id' => 92,
            'channel' => 0
        ]
    ],
    
    [
        'Report' =>
        [
            'id' => 18,
            'channel' => 0
        ]
    ]
];

// Output array will hold channel_N => count pairs
$result = [];

// Loop over all reports
foreach ($a as $report => $values)
{
    // Key takes form of channel_ + channel number
    $key = "channel_{$values['Report']['channel']}";
    
    if (!isset($result[$key]))
        // New? Count 1 item to start.
        $result[$key] = 1;
    else
        // Already seen this, add one to counter.
        $result[$key]++;
}

var_dump($result);
/*
Output:
array(2) {
  ["channel_1"]=>
  int(1)
  ["channel_0"]=>
  int(2)
}
*/
Sign up to request clarification or add additional context in comments.

Comments

1

You can easily do this without a loop using array_column() and array_count_values().

$reports = array_column($array, 'Report');
$channels = array_column($reports, 'channel');
$counts = array_count_values($channels);

$counts will now equal an array where the key is the channel, and the value is the count.

Array
(
    [1] => 1
    [0] => 2
)

2 Comments

Thanks Grumpy as well!
@Vova No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.