2016-11-21 41 views
0

我想有一個數組下面這個模式:值添加到一個存在的數組保持相同的密鑰

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

每一個項目(包括鍵)來自查詢。所以,我已經試過,包括以下列方式項:

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

這工作得很好,如果我手動硬編碼數據。

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

我得到以下錯誤:

Fatal error: Unsupported operand types

P.S.然而,通過MySQL的數據迭代時失敗$value['type']只包含「1」或「2」。

+0

我假設你重挫整個子陣列。更新一個鍵:'$ array [1] ['es'] = 23',然後'$ array [1] ['pt'] = 47'等等 – Progrock

回答

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); 

輸出:

array (
    'car' => 
    array (
    'br' => 24, 
    'es' => 40, 
), 
    'boat' => 
    array (
    'es' => 1, 
), 
) 
相關問題