Rosamunda Rosamunda - 2 months ago 10
JSON Question

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.

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) {
...
...
...
}
}

Answer

you can try this code dude!

$obj['fecha'] = $fechaMensaje;
$obj['autor'] = $userEmail;
$obj['mensaje'] = $mensaje;

//insert obj to data array
$data[] = $obj;

// encoding to json 
$json = json_encode($data);

hope it helps dude!

Comments