有人能解释为什么这个特殊的php数组不会使用json_encode正确编码为json吗?

时间:2016-08-06 18:18:02

标签: php json

这是我从远程api调用得到的数组:

Array ( [49] => Array ( [username] => Rocky [email] => rocky@rocky.com ) [50] => Array ( [username] => Ricky [email] => ricky@ricky.com ) )

json_encode给了我这个:

"Array\n(\n [49] => Array\n (\n [username] => Rocky\n [email] => rocky@rocky.com\n )\n\n [50] => Array\n (\n [username] => Ricky\n [email] => ricky@ricky.com\n )\n\n)\n"

我需要可以作为对象远程访问的json,但是这个字符串不起作用。

我正在使用此curl请求访问此数据:

<?php 

$post = [
    'api_key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    ];

$host = "http://xxxxxxxxxx.com/yardsale/get_clients.php";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $host);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($ch, CURLOPT_REFERER, "http://www.xxxxxxxxx.com");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)');
    $result = curl_exec($ch);
    curl_close($ch);


    echo $result;

?>

1 个答案:

答案 0 :(得分:1)

我认为存在数组问题,您可以更改类似的数组格式: -

<?php 
$arr=array( '49' => array('username'=> 'rocky', 'email'=> 'rocky@rocky.com'),'50' => array('username'=> 'mohit', 'email'=> 'mohit@mohit.com'));
$test_arr= json_encode($arr);
echo $test_arr;
?>

以上json的输出:

{"49":{"username":"rocky","email":"rocky@rocky.com"},"50":{"username":"mohit","email":"mohit@mohit.com"}}