php 在laravel控制器中将数组转换为json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40970955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:17:47  来源:igfitidea点击:

convert an array to json in laravel controller

phpjsonlaravel

提问by ajussi

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

嘿伙计们,我又有问题了。这次是我的 Laravel 项目。

I have a controller function like this:

我有一个这样的控制器功能:

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

And my $request->skulooked like this:

我的$request->sku看起来像这样:

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

but i need the json file like this:

但我需要这样的 json 文件:

[{"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?

我想我必须在 foreach 循环中做到这一点,对吗?任何人都可以帮助我吗?

回答by AddWeb Solution Pvt Ltd

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

在应用之后,您需要将数组转换为正确的形式,json_encode()如下所示:

$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.

希望这对你有用。

回答by Julien Lachal

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

使用$encodedSku = json_encode($request->sku);,您将拥有一个正确的 JSON 而不是数组。