简体   繁体   中英

PHP array count values and output new array

I have a PHP array that looks like this...

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

    [item2] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
            [3] => 1
            [4] => 1
            [5] => 2
        )

)

I am trying to count the values and output a new array that looks like this...

Array
(
    [item1] => Array
        (
            [1] => 3
        )

    [item2] => Array
        (
            [1] => 5
            [2] => 1
        )
)

I have tried to get the count by doing this...

print_r(array_count_values($myarray));

But this is not working for me, is there a way to count the values and creaye the new array all in one statement?

You're on the right track, but you need to apply array_count_values() to each subarray, not the parent array.

$arr = [
    'item1' => [1, 1, 3],
    'item2' => [1, 1, 1, 2, 1],
    'item3' => [1, 2, 2, 2, 3, 3, 3, 3, 3, 3]
];

$totals = array_map('array_count_values', $arr);

print_r($totals);

Results in

Array
(
    [item1] => Array
        (
            [1] => 2
            [3] => 1
        )

    [item2] => Array
        (
            [1] => 4
            [2] => 1
        )

    [item3] => Array
        (
            [1] => 1
            [2] => 3
            [3] => 6
        )

)

So, as @deceze advised - it is:

// applying `array_count_values` to each element of `$array`
print_r(array_map('array_count_values', $array));

You have array into an another array, it means you can't use array_count_values() with this way, either use array_map() or use foreach and save data into one another array like:

<?php
$array = array(
      'item1'=>array(1,1,1),
      'item2'=>array(1,1,1,1,1,2)
  );

$newArray = array(); // your new array
foreach ($array as $key => $value) {
  $newArray[$key] = array_count_values($value);
}
echo "<pre>";
print_r($newArray);
?>

Result:

Array
(
    [item1] => Array
        (
            [1] => 3
        )

    [item2] => Array
        (
            [1] => 5
            [2] => 1
        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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