Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode array to JSON string without array indexes

Tags:

json

arrays

php

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?

like image 903
PeterInvincible Avatar asked Dec 01 '14 16:12

PeterInvincible


People also ask

How do you convert a JSON array to a string?

Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.

Can JSON encode arrays?

Limitations. jsonencode does not support complex numbers or sparse arrays. Objects must have public properties encoded as name-value pairs with get methods defined on the object properties.

What is Json_encode?

The json_encode() function is used to encode a value to JSON format.

What does Json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


1 Answers

You want PHP's array_values() function:

$json_out = json_encode(array_values($your_array_here));
like image 154
Kevin_Kinsey Avatar answered Sep 20 '22 19:09

Kevin_Kinsey