138

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?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87

4 Answers4

238

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)).
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Nguyễn Văn Vinh
  • 2,754
  • 1
  • 14
  • 11
77

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]
Boris Guéry
  • 47,316
  • 8
  • 52
  • 87
  • 1
    Thanks for giving me the clue of indexed array :) the problem was i indexed it in such a way that the id was also the id of the array instead of a sequential id and json_encode didn't pick it up as an array but as in object instead because the array wasn't sequential its fixed now thanks for all your help guys :) –  Jun 25 '12 at 19:30
  • Not true. Some libraries do encode associative arrays as arrays with index as one of element properties. – Gustavo Jun 18 '13 at 01:11
  • I don't understand what you mean - the array in Martin's answer is non indexed, and that's valid JSON. – And Finally Oct 23 '14 at 19:26
  • @AndFinally, the array in Martin's answer *is* actually indexed, implicitly. Omitting index results in an indexed array starting from zero. – Boris Guéry Apr 06 '15 at 21:19
  • This answer didn't quite provide what the OP wanted at the time they posted the question (unsurprisingly, since what the OP wanted was impossible), and their edits to it since then have left this answer seemingly wildly wrong given the current state of the question. You can't delete this answer, since it's accepted, but perhaps flag for a moderator to delete it for you? Since it has over 5 upvotes, you'll keep your rep. – Mark Amery Nov 26 '15 at 19:32
2

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

Robert Sinclair
  • 4,550
  • 2
  • 44
  • 46
  • doesn't relate to the question asked by OP. OP specifically asked encoding issue encountered using `json_encode` – pg2286 Jun 21 '17 at 02:23
  • 1
    how is this not related? this shows an example of using json_encode so it turns the data into a readable array. OP's question is "How can I get json_encode to encode my array as an array" my bit of code does just that.. I'm gussing it's the word "Encode" that's causing you greef? By 'encode' he means 'turns into'. That's not a reason to downvote. – Robert Sinclair Jun 21 '17 at 17:29
  • oh I see your point now, that you would recommend something like this `$serialized = json_encode($nonContiguousArray);` `$unserialize = json_decode($serialized, true);` finally `finallySerializedInArrayFormat = json_encode($unserialize);` if this is what you are intending you are right, but seemed like a little winded solution. – pg2286 Jun 23 '17 at 20:03
-3

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>
Y0Gi
  • 423
  • 4
  • 10