MiskoPeterka
MiskoPeterka

Reputation: 31

how to count the number of items in a array and multiply with specifik key=>value

I'm struggling with counting the unique names in array and multiplying with specific value in the same array. Here is my multidimensional array:

Array
(
[0] => Array
        (

            [id] => 001
            [name] => Lamborgini
            [quantity] => 1
            [addon] => 1
        )

[1] => Array
        (
            [id] => 002
            [name] => Ferarri
            [quantity] => 1
            [addon] => 2
        )

[2] => Array
        (
            [id] => 003
            [name] => Lamborgini
            [quantity] => 2
            [addon] => 1
        )

[3] => Array
        (
            [id] => 004
            [name] => Ferarri
            [quantity] => 8
            [addon] => 2
        )   

[4] => Array
        (
            [id] => 005
            [name] => Lamborgini
            [quantity] => 2
            [addon] => 2
        )           
)

I want to count the unique names and quantity for each name, so the result should be:

[Lamborgini] => 3
[Ferarri] => 9

If i use

$counts = array_count_values(array_column($array, 'name'));

It will only count the numbers of unique Ferrari's and Lamborgini's but not adding the quantity to the array.

[Lamborgini] => 2
[Ferarri] => 2

How can i resolve this? I'm using PHP.

Thanks, Misko

Upvotes: 0

Views: 100

Answers (1)

user8034901
user8034901

Reputation:

Simply foreach loop over your array and add the relevant data to a new array:

$counts = array();
foreach ( $array as $item ) {
  if (!isset($counts[$item['name']])) {
    $counts[$item['name']] = $item['quantity'];
  } else {
    $counts[$item['name']] += $item['quantity'];
  }
}
print_r($counts);

$array is the name of your array, $counts is an array that will hold the counted results

Upvotes: 1

Related Questions