17

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 2

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You should initiate the associative array (sku, quantity) when creating the index $incI otherwise you'll get tons of warnings
@JulienLachal I tested my code at phpFiddle before I place it here and working fine without any single error. Hope you understand.
@ajussi: Happy to help you!
10

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

2 Comments

aaah! it change, you are right.. but it does not have the sku_id key
then you'll have to change the keys in the array, or create a new array from your first one. json_encode cannot guess the keys you need ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.