将 json 转换为多维 PHP 数组
Convert a json to multi-dimensional PHP array
我已将以下 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;
}
它returns以下预期结果
array (
'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' => NULL,
)
但我还需要将 'value' 转换为数组。这样我就可以拥有一个多维 PHP 数组。所以我希望得到类似
的东西
array (
'key' => 'levels',
'value' => array(
array('role_id'=>1, 'access_level_id'=>3),
array('role_id'=>2, 'access_level_id'=>1),
array('role_id'=>3, 'access_level_id'=>2)
)
'description' => NULL,
)
但是在我的 Laravel 方法中,我执行以下操作:
public function share_doc(Request $request){
$req=$request->all();
Log::debug(json_decode($req['value'],true));
return;
}
试图将作为 'value' 收到的 json 转换为 PHP 数组,它 returns 什么都没有 - 即没有值,没有数组,没有字符串。什么都没有。
所以,我在这里的挣扎是如何将作为 'value' 收到的整个 json 字符串从请求转换为 PHP 数组,以便我可以循环访问项目PHP
感谢您的帮助
您的问题是 value
元素无效 JSON,因为没有引用键。对于您提供的示例数据,您可以使用 preg_replace
and then json_decode
更改后的值进行修复:
$x['value'] = json_decode(preg_replace('/(\w+)(?=:)/', '""', $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] =>
)
我已将以下 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;
}
它returns以下预期结果
array ( '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' => NULL, )
但我还需要将 'value' 转换为数组。这样我就可以拥有一个多维 PHP 数组。所以我希望得到类似
的东西array ( 'key' => 'levels', 'value' => array( array('role_id'=>1, 'access_level_id'=>3), array('role_id'=>2, 'access_level_id'=>1), array('role_id'=>3, 'access_level_id'=>2) ) 'description' => NULL, )
但是在我的 Laravel 方法中,我执行以下操作:
public function share_doc(Request $request){
$req=$request->all();
Log::debug(json_decode($req['value'],true));
return;
}
试图将作为 'value' 收到的 json 转换为 PHP 数组,它 returns 什么都没有 - 即没有值,没有数组,没有字符串。什么都没有。
所以,我在这里的挣扎是如何将作为 'value' 收到的整个 json 字符串从请求转换为 PHP 数组,以便我可以循环访问项目PHP
感谢您的帮助
您的问题是 value
元素无效 JSON,因为没有引用键。对于您提供的示例数据,您可以使用 preg_replace
and then json_decode
更改后的值进行修复:
$x['value'] = json_decode(preg_replace('/(\w+)(?=:)/', '""', $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] =>
)