下面我有數組創建新的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並使用。= +來獲得總和?但我失去了那裏,
感謝,
請格式化這個 。並把一些有效的json數據 – Mahi
你從數據庫中獲取這些數據嗎? – peterm
@peterm,是的我從數據庫中獲取數組輸出,並且想要創建PHP循環來輸出JSON – rjcode