adeguntoro's avatar

How to convert array into json ?

I try to save array into my database, it works, but not like what i want. My current result :

[{"total":"1 kg"},{"ingredients":"eggs"},{"total":"2 liter"},{"ingredients":"oil"}]}

and this is what i want :

[{
"total":"1 KG", "ingredients":"Eggs"
},{
"total":"2 liter","ingredients":"Milk"
}]

ar this time i just use this in my controller :

        $total       = $request->input('total');
        $ingredients = $request->input('ingredients');
        foreach ($total as $index => $side ) {
            $array[$side] = $ingredients[$index];
        }
        $data =  json_encode($array);
    return $data
0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

$total       = $request->input('total');
        $ingredients = $request->input('ingredients');
        foreach ($total as $index => $side ) {
            $array[$index]['ingredients'] = $ingredients[$index];
$array[$index]['total'] = $side;
        }
        $data =  json_encode($array);
    return $data

Please or to participate in this conversation.