将数组编码为不带数组索引的JSON字符串 [英] Encode array to JSON string without array indexes
问题描述
我正在使用以下语法从Javascript向数据库发送JSON字符串:
I'm sending a JSON string to the database from Javascript, with the following syntax:
["Product1","Product2","Product3"]
在我将这些数据简单地放入数据库中而不用php对其进行解码之前,在恢复后再次使用它时,它就没有问题了.
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.
但是现在我需要对字符串中的数据进行一些更改,因此我在PHP中对其进行了解码,这将导致如下所示的数组:
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
//)
我的问题是,当我将此数组编码回JSON时,字符串的格式如下:
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"}
我需要编码的字符串与我的javascript创建的字符串相同,因此没有数组索引.有没有简单的方法可以做到这一点?
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?
推荐答案
您想要PHP的 array_values()
函数:
You want PHP's array_values()
function:
$json_out = json_encode(array_values($your_array_here));
这篇关于将数组编码为不带数组索引的JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!