Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert an array to json in laravel controller

Tags:

json

php

laravel

Hy Guys, I have a problem again. and this time with my laravel project.

I have a controller function like this:

public function postDetail(Request $request)
{
  $product_requests = $request->sku;
  $arr = [];
}

And my $request->sku looked like this:

[612552892 => ['quantity' => '1'], 625512336 => ['quantity' => '10']]

but i need the json file like this:

[{"sku_id": 612552892, "quantity": "1"}, {"sku_id": 625512336, "quantity": "10"}]

so, should i make the key too? but.. How ?

and I think I have to make it in foreach loop right? anyone can help me?

like image 678
ajussi Avatar asked Dec 05 '16 09:12

ajussi


2 Answers

Use $encodedSku = json_encode($request->sku); and you'll have a proper JSON instead of an Array.

like image 120
Julien Lachal Avatar answered Oct 14 '22 03:10

Julien Lachal


You need to convert array into proper form after that apply json_encode()like below:

$arrSku = array('612552892' => array('quantity' => 1), '625512336' => array('quantity' => 10) );

$arrNewSku = array();
$incI = 0;
foreach($arrSku AS $arrKey => $arrData){
    $arrNewSku[$incI]['sku_id'] = $arrKey;
    $arrNewSku[$incI]['quantity'] = $arrData['quantity'];
    $incI++;
}

//Convert array to json form...
$encodedSku = json_encode($arrNewSku);

print('<pre>');
print_r($encodedSku);
print('</pre>');

//Output:
[{"sku_id":612552892,"quantity":1},{"sku_id":625512336,"quantity":10}]

Hope this will work for you.

like image 26
AddWeb Solution Pvt Ltd Avatar answered Oct 14 '22 05:10

AddWeb Solution Pvt Ltd