119

I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:

[["Afghanistan",32,12],["Albania",32,12]]

However, it is returning as:

{"2":["Afghanistan",32,12],"4":["Albania",32,12]}

How can I remove these row numbers without using any regex trickery?

3
  • 8
    ["2":["Afghanistan",32,12],"4":["Albania",32,12]] is not even valid JSON, so I doubt you get that. If your top level array is associative just call array_values() to get consecutive indexed elements. Commented Jul 30, 2012 at 12:59
  • 1
    of interest to this topic too: php.net/manual/en/function.json-encode.php#105923 Commented Jul 30, 2012 at 13:07
  • @Ben link no longer seems to work Commented Oct 1, 2021 at 4:07

4 Answers 4

223

If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.

Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:

Example:

// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
  2 => array("Afghanistan", 32, 13),
  4 => array("Albania", 32, 12)
);

// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
6
  • 2
    I've ended here when I found out that json_encode converted an array to object for no apparent reason when the array has only one item in it after being filtered by array_filter. I don't know if the array index has something to do with this disgusting php "bug", but array_values sorted it out for me. From now on.. there is no json_encode of an array without array_values being called. Commented Jul 13, 2016 at 18:29
  • 2
    @MarBar If the array has a non-numeric string key or a numeric key out of sequence, json_encode() will produce an {} object rather than an array [] since JavaScript/JSON has no other way to represent such a structure. But yes, you can strip the keys with array_keys() if they are not needed in the resultant json string. Commented Jul 13, 2016 at 18:35
  • @MichaelBerkowski: i'm getting the same issue with a composite primary key from a db table, where i need to do first: mysqli_fetch_assoc and then array_values... i'm wonder if this is the most performant way to get true arrays with a lot of data ... should i rewrite my custom json_encode? what is your (appreciated) opinion about that? Commented Oct 19, 2017 at 20:47
  • 1
    @deblocker Hard to guess hour composite key fits in. Generally PHP's array_*() functions are all very efficient. On a small array, I generally prefer to use a few single action array_* functions if I can avoid loops. But if your mysqli_result is large you may not want to compile it all into an array at once then call array_values(). Instead you may be better to append rows to an array while fetching. All speculation though because I don't know what your code looks like. Commented Oct 19, 2017 at 20:55
  • 1
    @Gem That depends very much on the structure of the XML you need to create because XML elements must be somehow named. There are examples in stackoverflow.com/questions/1397036/… Commented Nov 16, 2018 at 13:42
26

json_encode() function will help you to encode array to JSON in php.

if you will use just json_encode function directly without any specific option, it will return an array. Like mention above question

$array = array(
  2 => array("Afghanistan",32,13),
  4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]

Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below

<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"} 
?>
0
4

I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.

For example:

[
    3 => 'a',
    2 => 'b',
    1 => 'c',
    0 => 'd'
]

Will return:

{
    0: 'd',
    1: 'c',
    2: 'b',
    3: 'a'
}

So the solution in this case, is to use array_reverse before encoding it to json

11
  • I think the array_values solution written by @Michael Berkowski is more universal and it works also in your case. Commented Feb 28, 2020 at 18:51
  • @mickmackusa I disagree that it should be deleted. While it might not be useful to the OP, it can still be useful to other people with a similar problem. Commented Jun 2, 2021 at 10:03
  • This was way too long ago. I remember that I just wanted to answer another case that might not be obvious, and if someone has a similar issue, and will scroll through, this will give them a hint. I don't think there's any harm in that. It's true, that one might blindly follow @Michael Berkowski's solution, but if you already think that's not your issue, or trying to understand why is that your issue, then this might be it... Commented Jun 2, 2021 at 10:03
  • Every answer must only address the question within the scope of the question. Extending the question by altering the sample data is not good -- otherwise we would see loads of pages suffer from scope creep. There are millions of pages here, find a more appropriate page to post this advice on. array_reverse() is absolutely no benefit to the OP's question. Commented Jun 2, 2021 at 10:05
  • Age of a post is not a factor in this decision. Researchers don't care how old a page/post is. They want the best advice for the given question with no time wasted reading off-topic/irrelevant stuff. Commented Jun 2, 2021 at 10:08
3

I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:

$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");

It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.

Hope that helps

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.