开发者

How do I return an array in a response

开发者 https://www.devze.com 2023-04-08 05:57 出处:网络
I\'m trying to return an array in HTTP response. I\'m thinking to return array as JSON objects. I\'m doing echo json_encode($arr)but I get nothing in the response.

I'm trying to return an array in HTTP response. I'm thinking to return array as JSON objects. I'm doing echo json_encode($arr) but I get nothing in the response.

UPDATE: I'm running a version of PHP that does not have json_encode method. json_encode was introduced in PHP 5.2. So I guess question is how would you return an array without using json_encode?

     $arr = array();
    foreach($_POST['ids'] as $id)
    {
        $arr[$id] = $id;
    }   
    echo json_encode($arr);

    return;

Here are contents of my array:

array(18) {
  [156795]=开发者_开发问答>
  string(6) "156795"
  [156800]=>
  string(6) "156800"
  [4292]=>
  string(4) "4292"
  [796053]=>
  string(6) "796053"
  [660520]=>
  string(6) "660520"
 ...


Make sure to set the proper MIME type when sending back JSON:

header('Content-Type: application/json');
echo json_encode($arr);


json_encode() requires PHP 5.2.0 or above. Make sure your host hasn't compiled PHP with the --disable-json flag. Both of these can be checked with the phpinfo() function. The code you've posted so far works fine for me.


json encode should do it with no problems. When I pump that data into an array it works fine. Can you post some code for building the array? What version of PHP are you using?


plz use json validator to make sure ur json is correct

look I did this & it worked fine

 $arr = array();
 $i=0;
    while($i<10)
    {
        $arr[$i] = $i;
        $i++;
    }   
    echo json_encode($arr);

    return;
0

精彩评论

暂无评论...
验证码 换一张
取 消