0

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".

1
  • I assume you are clobbering the entire sub array. To update one key do: $array[1]['es'] = 23, and then $array[1]['pt'] = 47 etc. Commented Nov 21, 2016 at 10:38

1 Answer 1

2
<?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,
  ),
)
Sign up to request clarification or add additional context in comments.

Comments

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.