18

I'm sending a JSON string to the database from Javascript, with the following syntax:

["Product1","Product2","Product3"]

Before I simply put this data in my database without decoding it in php, and it worked without problems when using it again after retreival.

However now I need to make a few changes to the data in the string, so I decode it in PHP, which will result in an array like so:

print_r(json_decode($_POST["myjsonstring"]));
//outputs
//Array
//(
//    [0] => Product1
//    [2] => Product2
//    [3] => Product3
//)

My problem is that when I encode this array back to JSON, the string's format will be the following:

{"0":"Product1","2":"Product2","3":"Product3"}

I need the encoded string to be the same as my javascript creates, so without the array indexes. Is there an easy way to do this?

PeterInvincible
  • 2,230
  • 5
  • 34
  • 62
  • 1
    Why the missing index in your array? I think you are not showing all the code touching this array. If you don't have a continuous set of numerical index values, the json_encode process will treat it like an associative array and encode to object notation instead of array notation. – Mike Brant Dec 01 '14 at 16:35

1 Answers1

39

You want PHP's array_values() function:

$json_out = json_encode(array_values($your_array_here));
Glavić
  • 42,781
  • 13
  • 77
  • 107
Kevin_Kinsey
  • 2,285
  • 1
  • 22
  • 23
  • $json_out = json_encode(array_values($your_array_here)); – Kevin_Kinsey Dec 01 '14 at 16:35
  • 1
    Put that example in your answer. – Glavić Dec 01 '14 at 16:35
  • The missing index might be important, though. – Sirko Dec 01 '14 at 16:36
  • I'm stumped. The [manual](http://php.net/manual/en/function.array-values.php) says that the `array_values()` function "Returns an **INDEXED** array of values." And when I do `$array2 = array_values($array1)`, both arrays continue to contain indexes of this format: `[0] =>` – rudminda Apr 29 '17 at 17:38
  • An indexed array is an array that is numerically indexed. Per manual, "array_values() returns all the values from the array and indexes the array numerically." Or do you mean that all the values are empty/blank? – Kevin_Kinsey May 01 '17 at 19:03
  • 1
    Is there any way to encode the array without numerical indexes, or any indexes at all? Something like this: `{ "id": 1, "geometry": [ 15.12412412412, 22.12431241241 ] }` – No Reply Dec 12 '19 at 11:47
  • Well, PHP has to keep track of array members *somehow*, so, no, an array without indexes can't (doesn't?) exist. But getting your desired result is easy enough: ```$geometry = [15.12412412412, 22.1243124124]; $myarray = [ 'id' => 1, 'geometry' => $geometry ]; echo json_encode($myarray);``` – Kevin_Kinsey Dec 13 '19 at 14:44