How do I encode a PHP array to a JSON array, not object?

前端 未结 4 866
你的背包
你的背包 2020-12-09 20:39

I am trying to json_encode an array which is returned from a Zend_DB query.

var_dump gives: (Manually adding 0 member does not change the picture.)

a         


        
相关标签:
4条回答
  • 2020-12-09 21:23

    i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:

    var myJsVar =  <?php echo json_encode($var); ?> ;    -------> NOT WORKING  
    var myJsVar = '<?php echo json_encode($var); ?>' ;   -------> WORKING
    
    0 讨论(0)
  • 2020-12-09 21:27

    How are you setting up your initial array?

    If you set it up like:

    array(
     "1" => array(...),
     "2" => array(...),
    );
    

    then you don't have an array with numeric indexes but strings, and that's converted to an object in JS world. This can happen also if you don't set a strict order (i.e. starting at 0 instead of 1).

    This is a shot in the dark, however, because I can't see your original code: try setting your array without using keys at all in the first place:

    array(
     array(...),
     array(...),
    );
    
    0 讨论(0)
  • 2020-12-09 21:27

    Added information that expands on Seb's answer.

    php > print json_encode( array( 'a', 'b', 'c' ) ) ;
    ["a","b","c"]
    php > print json_encode( array( 0 => 'a',  1 => 'b', 2 => 'c' ) ) ;
    ["a","b","c"]
    php > print json_encode( array( 1 => 'a',  2 => 'b', 3 => 'c' ) ) ;
    {"1":"a","2":"b","3":"c"}
    php > 
    

    Note: its formatting it this way with good cause:

    If you were to send

    {"1":"a","2":"b","3":"c"}
    

    as

    ["a","b","c"]
    

    When you did $data[1] in Php you would get back "a", but on the JavaScript side, you would get back "b" .

    0 讨论(0)
  • 2020-12-09 21:29

    A common way to test for a traditional, continuous array in php is to check for an index '0'. Try adding that to your array, it'll probably considering it an array instead of hashmap.

    0 讨论(0)
提交回复
热议问题