John Stage
John Stage

Reputation: 1

Add values to an existent array keeping the same key

I want to have an array following this pattern:

[1] => Array
       (
           [es] => 11
           [pt] => 22
           [br] => 333
       )
[2] => Array
       (
           [es] => 1221
           [pt] => 23442
           [br] => 344433
       )

Every item (including the key) comes from a query. So, I've tried including items in the following way:

array[1]= array('es'=>'11');
array[1]+= array('pt'=>'22');

This works fine if I hardcode the data manually. However, it fails when iterating through the mysql data:

foreach($elements as $value) {          
    $available = $value['purchased'] - $value['used'];
    $credits[$value['type']]= array($value['country']=>$availableCredit);
}

I get the following error:

Fatal error: Unsupported operand types

P.S. $value['type'] only comprises "1" or "2".

Upvotes: 0

Views: 43

Answers (1)

Progrock
Progrock

Reputation: 7485

<?php
$elements = [
    [
        'type' => 'car',
        'country' => 'br',
        'purchased' => 47,
        'used' => 23
    ],
    [
        'type' => 'car',
        'country' => 'es',
        'purchased' => 50,
        'used' => 10
    ],
    [
        'type' => 'boat',
        'country' => 'es',
        'purchased' => 100,
        'used' => 99
    ],
];

foreach($elements as $value) {
    $difference = $value['purchased'] - $value['used'];
    $credits[$value['type']][$value['country']] = $difference;
}

var_export($credits);

Output:

array (
  'car' => 
  array (
    'br' => 24,
    'es' => 40,
  ),
  'boat' => 
  array (
    'es' => 1,
  ),
)

Upvotes: 2

Related Questions