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?
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.
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.
The json_encode() function is used to encode a value to JSON format.
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.
You want PHP's array_values()
function:
$json_out = json_encode(array_values($your_array_here));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With