114

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57
  • 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. – Felix Kling Jul 30 '12 at 12:59
  • 1
    of interest to this topic too: http://www.php.net/manual/en/function.json-encode.php#105923 – Ben Jul 30 '12 at 13:07
  • @Ben link no longer seems to work – 8ctopus Oct 01 '21 at 04:07
  • 1
    @8ctopus yeah, it's 9 years old I guess.. – Ben Oct 06 '21 at 02:57

4 Answers4

214

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]]
Community
  • 1
  • 1
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 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. – Mar Bar Jul 13 '16 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. – Michael Berkowski Jul 13 '16 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? – deblocker Oct 19 '17 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. – Michael Berkowski Oct 19 '17 at 20:55
  • @MichaelBerkowski Like same how can i convert Object to XML? – Gem Nov 16 '18 at 06:18
  • 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 https://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml – Michael Berkowski Nov 16 '18 at 13:42
22

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"} 
?>
5

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

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Inc33
  • 1,747
  • 1
  • 20
  • 26
  • I think the `array_values` solution written by @Michael Berkowski is more universal and it works also in your case. – Jacopo Pace Feb 28 '20 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. – Donald Duck Jun 02 '21 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... – Inc33 Jun 02 '21 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. – mickmackusa Jun 02 '21 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. – mickmackusa Jun 02 '21 at 10:08
  • While it's not answering the OP's question directly, it is completely within scope. I myself posted to this one, because was having the issue I just posted, and wasn't able to find an answer, hence if this post was available, I would've found it. As a developer, I keep finding myself in the position where answers like this one complete the answer I'm seeking for, and not the answer that directly answers OP's question – Inc33 Jun 02 '21 at 10:10
  • Look at how upvoted answers which do not answer the question will make researchers waste their time reading something that cannot work. https://stackoverflow.com/a/37500756/2943403 Being useful is not enough -- the answer MUST answer the question. – mickmackusa Jun 02 '21 at 10:13
  • I'm sure there are lots of more irrelevant answers to pick on, than this... where the stand is already 2 against 1 Besides, it has 5 upvotes, which means people do find it useful – Inc33 Jun 02 '21 at 10:15
  • I just think that anything that brings real value should be preserved, while duplicates/spam should be removed. This does bring real value, which I know from experience, and posted it here, because this was the question I ran into while looking for an answer. You might not see that value, but I'm sure enough people would disagree, which means that one person's philosophy shouldn't necessarily outweigh everyone else's in this case. Let's bring this to chat if you want to add to it, or bring in other moderators – Inc33 Jun 02 '21 at 10:24
  • And one last thing I want to add, is that I do disagree that this wastes anybody's time, as anybody who scrolls over the best answer, is already past looking for the straight answer. That's the whole point of having the best answer feature – Inc33 Jun 02 '21 at 10:31
  • Thanks, some how this solutions works for me.. – ramprakash jagadeesan Oct 18 '22 at 17:14
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

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
mstone
  • 39
  • 3