2016-11-26 154 views
0

下面我有數組創建新的JSON,與價值觀的總和陣列

Array ([0] => Array ([user_name] => Jack1 [amount] => 100.00 [category_name] => Trial1) [1] => Array ([user_name] => Jack1 [amount] => 150.00 [category_name] => Trial2) [2] => Array ([user_name] => Jack1 [amount] => 200.00 [category_name] => Trial1) [3] => Array ([user_name] => Jack2 [amount] => 200.00 [category_name] => Trial2) [4] => Array ([user_name] => Jack2 [amount] => 200.00 [category_name] => Trial1) [5] => Array ([user_name] => Jack2 [amount] => 200.00 [category_name] => Trial2) 

什麼,我想送有JSON具有以下格式

它會得到一些平等類別名稱,然後發送它作爲json。

[{'user_name': Jack1, 'trial1':"300", 'trial2':150"" }, {'user_name': Jack2, 'trial1':"200", 'trial2':400"" }] 

綜上所述,我想用戶名是唯一的,然後把所有種類與名稱和每個類別的用戶的總和,

下面試過,

$new_array = array(); 

     foreach ($expense_array['x'] as $a) 
     { 
      if (!isset($new_array[$a['user_name']]['amount'])) 
      { 
       $new_array[$a['user_name']]['amount'] = 0; 
      } 

      $new_array[$a['user_name']] = array(
        'user_name' => $a['user_name'], 
        'category_name' => $a['category_name'], 
        'amount' => $new_array[$a['user_name']]['amount'] + $a['amount']); 

     } 
echo json_encode(array_values($new_array)); 

這隻輸出trai1類別,而不是按要求JSON

我該如何做到這一點? 想要獲得foreach循環,然後比較category_name並使用。= +來獲得總和?但我失去了那裏,

感謝,

+0

請格式化這個 。並把一些有效的json數據 – Mahi

+0

你從數據庫中獲取這些數據嗎? – peterm

+0

@peterm,是的我從數據庫中獲取數組輸出,並且想要創建PHP循環來輸出JSON – rjcode

回答

1

如果你傳遞數組到這個函數會返回所需的JSON字符串:

function create_json($data) 
{ 
    $output = []; 

    foreach ($data as $stats) 
    { 
     $key  = $stats['user_name']; 
     $category = strtolower($stats['category_name']); 
     $amount = $stats['amount']; 

     if (isset($output[$key])) 
     { 
      if (isset($output[$key][$category])) 
      { 
       $output[$key][$category] += $amount; 
      } 
      else 
      { 
       $output[$key][$category] = $amount; 
      } 
     } 
     else 
     { 
      $output[$key] = [ 
       'user_name' => $key, 
       $category => $amount, 
      ]; 
     } 
    } 

    return json_encode(array_values($output)); 
} 

輸出:

[ 
{"user_name":"Jack1","trial1":300,"trial2":150}, 
{"user_name":"Jack2","trial2":400,"trial1":200} 
] 
+0

幾乎在那裏,但我怎樣才能得到Jack1,2的所有類別金額的總和? – rjcode

+0

@rjcode,所以你想它輸出每個類別的總和和所有類別的總和?如果是這樣,那麼改變你的例子JSON來反映這一點,我會讓它匹配。 – Sane

+0

已更新JSON輸出 – rjcode