我有这个数组
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions']['name'] = 'blur';
$params_array['functions']['params']['radius'] = '0.0';
$params_array['functions']['params']['sigma'] = '2.0';
$params_array['functions']['save']['image_identifier'] = 'MY_CLIENT_ID';
我需要把它变成json。
所以我这样做:
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES);
结果是
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}}
但是,json的接收器API希望它形成略有不同,如下所示:
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":[{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}]}
区别:在“功能”之后:有这个括号[,它在最后关闭。
PHP以某种方式不会使用此括号创建json。
如何让PHP用这些括号创建json?
答案 0 :(得分:2)
你应该这样准备你的结构:
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions'][0]['name'] = 'blur';
$params_array['functions'][0]['params']['radius'] = '0.0';
$params_array['functions'][0]['params']['sigma'] = '2.0';
$params_array['functions'][0]['save']['image_identifier'] = 'MY_CLIENT_ID';
(将函数转换为数字索引数组。)
答案 1 :(得分:1)
因此接收器期望functions
是数组对象,但是您传递的是单个对象。将$params_array['functions']['name']
更改为$params_array['functions'][$functionIndex]['name']
答案 2 :(得分:0)
如果你有PHP 5.4.0或更高版本,你可以尝试使用标志JSON_FORCE_OBJECT
:
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES + JSON_FORCE_OBJECT);
答案 3 :(得分:0)
试试这个
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$function_array['name'] = 'blur';
$function_array['params']['radius'] = '0.0';
$function_array['params']['sigma'] = '2.0';
$function_array['save']['image_identifier'] = 'MY_CLIENT_ID';
$params_array['functions'] = array($function_array);
原因:
JSON_ENCODE
会将数组视为JSON OBJECT
,如果它与Key=>Value
一样
如果它是基于索引的json array
[0] => value
答案 4 :(得分:0)
好的,运行这个例子然后你就会知道如何实现它。
$params_array = array();
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['another_array'] = array("A","B","C");
echo json_encode($params_array );
结果:{“application_id”:“xxxxxxxxx”,“another_array”:[“A”,“B”,“C”]}