Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

json_encode PHP array as JSON array not JSON object

I have the following array in PHP:

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => name1
            [short_name] => n1
        )

    [2] => Array
        (
            [id] => 2
            [name] => name2
            [short_name] => n2
        )
)

I want to JSON encode it as a JSON array, producing a string like the following:

[  
    {  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    {  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
]

But when I call json_encode on this array, I get the following:

{  
    "0":{  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    "2":{  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
}

Which is an object instead of an array.

How can I get json_encode to encode my array as an array, instead?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See Arrays in RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format:

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

You are observing this behaviour because your array is not sequential - it has keys 0 and 2, but doesn't have 1 as a key.

Just having numeric indexes isn't enough. json_encode will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...