问题描述
我将以下json发送到我的API端点
{“ key”:“ levels”,“ value”:“ [[{role_id:1,access_level_id:3},{role_id:2,access_level_id:1},{role_id:3,access_level_id:2}]”“, “ description”:“”}
在后端,我作为Laravel请求收到了它,如下所示:
public function functionName(Request $request){
$req=$request->all();
Log::debug($req['value']);
return;
}
它返回以下预期结果
数组( '键'=>'级别', 'value'=>'[{{role_id:1,access_level_id:3},{role_id:2,access_level_id:1},{role_id:3,access_level_id:2}]', '描述'=> NULL, )
但是我还需要将“值”转换为数组。这样我就可以拥有一个多维PHP数组。所以我希望得到类似的东西
数组( '键'=>'级别', '值'=>数组( array('role_id'=> 1,'access_level_id'=> 3), array('role_id'=> 2,'access_level_id'=> 1), array('role_id'=> 3,'access_level_id'=> 2) ) '描述'=> NULL, )
public function share_doc(Request $request){
$req=$request->all();
Log::debug(json_decode($req['value'],true));
return;
}
尝试将作为“值”接收的json转换为PHP数组,它不返回任何内容-即。没有值,没有数组,没有字符串。没事。
所以,我在这里的难题是如何将请求中作为“值”接收的整个json字符串转换为PHP数组,以便可以使用PHP遍历所有项目。
谢谢您的帮助
解决方法
您的问题是value
元素不是有效的JSON,因为未引用键。对于您提供的示例数据,您可以先使用preg_replace
然后再通过json_decode
来更改值:
$x['value'] = json_decode(preg_replace('/(\w+)(?=:)/','"$1"',$x['value']),true);
print_r($x);
输出:
Array
(
[key] => levels
[value] => Array
(
[0] => Array
(
[role_id] => 1
[access_level_id] => 3
)
[1] => Array
(
[role_id] => 2
[access_level_id] => 1
)
[2] => Array
(
[role_id] => 3
[access_level_id] => 2
)
)
[description] =>
)