rjcode rjcode - 11 days ago 6
PHP Question

Create new JSON with sum of values in array

I have below array,

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 )


What i want to send to have JSON with below format

It will get some of Equal category name and then send it as json.

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


In summary, i want to username as unique and then put all category with name and sum of each category for that user,

Tried below,

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


This only output trai1 category, not as required JSON

How can i achieve this?
Was thinking to get
foreach
loop and then make compare of category_name and use .=+ to get sum? but i lost there,

Thanks,

Answer

If you pass the array into this function it will return the json string that you want:

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

Output:

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