Convert an Array to Json in Laravel Controller

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?

2 Answers

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.

3

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest