19

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?

1
  • 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. Commented Dec 1, 2014 at 16:35

1 Answer 1

40

You want PHP's array_values() function:

$json_out = json_encode(array_values($your_array_here));
Sign up to request clarification or add additional context in comments.

5 Comments

The missing index might be important, though.
I'm stumped. The manual 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] =>
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?
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 ] }
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);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.