使用数组中的值总和创建新的JSON

时间:2016-11-26 05:28:17

标签: php arrays 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格式低于

它将获得一些Equal类别名称,然后将其作为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并使用。= +来获得总和?但我输了,

谢谢,

1 个答案:

答案 0 :(得分: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}
]