1

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":["[email protected]"],
"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) "[email protected]" 
    } 
    ["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) "[email protected]" 
        ['mensaje']=> string(11) "lorem ipsum" 
    } 
    [1]=> array(3) { 
        ...
        ...
        ...       
    } 
}   
2
  • $data['fecha'][] you don't want that [] on the end - that's assigning the data as an array not a string which accounts for the different structure. Commented Sep 29, 2016 at 14:55
  • How about data[]['fecha'] = $fechaMensaje; and so on? Commented Sep 29, 2016 at 15:16

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

You can define another array, in the below case $some_var, to contain each array of data. Also remove [] on the end when assigning the values for $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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.