I have the following code where I store variables in an array and apart it stores 2 arrays of information within it.
$fonos =array();
$direccion = array();
foreach ($_POST['new_fono'] as $fono) {
$fonos[] = $fono;
}
foreach ($_POST['new_address'] as $address) {
$direccion[] = $address;
}
$data['result'] = array($name,$city,$obs,$email,$giro,$direccion,$fonos);
echo json_encode($data);;
In this way I show the variables you will save
alert(response.result[0]);
But how do I show the array
phones and address.
My result in devtool
{"result":["Name Cliente","City","qwe","[email protected]","Informatica",["Calle 1","Calle 2","Calle 3"],["123123123","456456456","789789789"]]}
Inside the
result
JSON key there is an array with several elements, and inside that array there are two other sub-arrays, one with the streets and the other with the phones.One way to read the JSON would be a normal reading for each key, asking when it is an array, in which case you can use
join
to extract the data that is in the sub-arrays, with any separator, which can be a line break , a comma, or another.For example:
the same way you print but you must use json_encode() to convert the array to String:
to display in an alert, display the array as a String representation of the object like so:
Example:
would show:
According to the json you show in your update:
The structure is actually an array (
result
) that contains 5 values ("Name Cliente", "City", "qwe", "[email protected]", "Informatica"
) and 2 arrays, one containing the streets (["Calle 1", "Calle 2", "Calle 3"]
) and the other containing the numbers (["123123123", "456456456", "789789789"]
)To obtain its values you can do it in this way:
This would have as output:
my advice is to define your result object with key-value. You could do it like this:
With this, now accessing each element is easier, you could access as:
Also, with this you are defining a structure that is easy to understand on reception (when reading the json, you can see that the key
name
refers to the name). Otherwise you would have to tell the recipient that 0 is name, 1 is address...This is how you can display it:
or in any case have one
console.log(response.result);
so that you can see your array by console