How do I `json_encode()` keys from PHP array?

前端 未结 4 1661
鱼传尺愫
鱼传尺愫 2020-12-03 10:59

I have an array which prints like this

Array ( [0] => 1691864 [1] => 7944458 [2] => 9274078 [3] => 1062072 [4] => 8625335 [5] => 8255371 [6         


        
相关标签:
4条回答
  • 2020-12-03 11:36

    You can force that json_encode uses an object although you’re passing an array with numeric keys by setting the JSON_FORCE_OBJECT option:

    json_encode($thearray, JSON_FORCE_OBJECT)
    

    Then the returned value will be a JSON object with numeric keys:

    {"0":1691864,"1":7944458,"2":9274078,"3":1062072,"4":8625335,"5":8255371,"6":5476104,"7":6145446,"8":7525604,"9":5947143}
    

    But you should only do this if an object is really required.

    0 讨论(0)
  • 2020-12-03 11:39

    This is defined behaviour. The array you show is a non-associative, normally indexed array. Its indexes are implicitly numeric.

    If you decode the array in PHP or JavaScript, you will be able to access the elements using the index:

    $temp_array = json_decode($temp_json);
    
    echo $temp_array[2]; // 9274078
    
    0 讨论(0)
  • 2020-12-03 11:46

    Because those are just the indices of the array. If you want to add some kind of name to each element then you need to use an associative array.

    When you decode that JSON array though it will come back out to 0, 1, 2, 3 etc.

    0 讨论(0)
  • 2020-12-03 12:00

    Use this instead:

    json_encode((object)$temp)
    

    This converts the array into object, which when JSON-encoded, will display the keys.

    If you are storing a sequence of data, not a mapping from number to another number, you really should use array.

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