[英]How to better format the JSON string generator with PHP json_encode()?
I'm saving data inside arrays with php's json_encode()
function and then encoding them into json strings in order to save them into a single database field. 我使用php的json_encode()
函数将数据保存在数组中,然后将它们编码为json字符串,以便将它们保存到单个数据库字段中。
This is what I've been doing: 这就是我一直在做的:
$fechaMensaje = $_POST['fechaMensaje'];
$mensaje = $_POST['mensaje'];
$estadoMensaje = 'abierto';
$data['fecha'][] = $fechaMensaje;
$data['autor'][] = $userEmail;
$data['mensaje'][] = $mensaje;
$datosMensaje = json_encode($data);
This does work, and it does creates a string like this: 这确实有效,并且确实创建了这样的字符串:
{
"fecha":["29-09-2016 11:12:51 AM"],
"autor":["demo@example.com"],
"mensaje":["lorem ipsum"]
}
This is the array I've got when decoding the string: 这是解码字符串时得到的数组:
{
["fecha"]=> array(1) {
[0]=> string(22) "29-09-2016 11:12:51 AM"
}
["autor"]=> array(1) {
[0]=> string(23) "demo@example.com"
}
["mensaje"]=> array(1) {
[0]=> string(11) "lorem ipsum"
}
}
Now, my question is, how may I change the way I'm generating the array in the first place, to get this output instead? 现在,我的问题是,如何首先改变生成数组的方式,以获取此输出? (having the three items in the same array, so when I do add more elements it's going to be more organized). (在同一数组中具有这三个项目,因此当我添加更多元素时,它将变得更有条理)。
{
["0"]=> array(3) {
['fecha']=> string(22) "29-09-2016 11:12:51 AM"
['autor']=> string(23) "demo@example.com"
['mensaje']=> string(11) "lorem ipsum"
}
[1]=> array(3) {
...
...
...
}
}
You can define another array, in the below case $some_var
, to contain each array of data. 您可以定义另一个数组,在以下情况下, $some_var
包含每个数据数组。 Also remove []
on the end when assigning the values for $data
. 分配$data
的值时,也请最后删除[]
。
$fechaMensaje = $_POST['fechaMensaje'];
$mensaje = $_POST['mensaje'];
$estadoMensaje = 'abierto';
$data['fecha'] = $fechaMensaje;
$data['autor'] = $userEmail;
$data['mensaje'] = $mensaje;
$some_var[0] = $data;
$datosMensaje = json_encode($some_var);
You can try this code: 您可以尝试以下代码:
$obj['fecha'] = $fechaMensaje;
$obj['autor'] = $userEmail;
$obj['mensaje'] = $mensaje;
//insert obj to data array
$data[] = $obj;
// encoding to json
$json = json_encode($data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.