Fabio97 Fabio97 - 4 months ago 8
JSON Question

Enter to elements of a Json object with php

I've got the following json object:

$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array ("n1"=>"fabio",
"n2"=>"marcolino",
"n3"=>"lauretta")
);
$p = json_encode($dati);
echo $p;


How can I enter the
n1
element to show
fabio
as output?

$p.str.n1
doesn't work. How can I do this?

Besides, how can I show
fabio
,
marcolino
,
lauretta
using a
for
loop?

for ($i=1; $i<=3; $i++) {
$dati = array(
"data" => array(
'address_complete'=>$data->results[0]->formatted_address,
'address_square'=>$data->results[0]->address_components[1]->long_name,
'location'=>$data->results[0]->address_components[2]->long_name,
'postal_code'=>$data->results[0]->address_components[7]->long_name,
'data_ora'=>$tmp_date
),
"str" => array (
"n".$i=>"fabio",
"n".$i=>"marcolino",
"n".$i=>"lauretta")
);
//$p = json_encode($dati);
echo $dati[str]["n".$i];
}


How can I fix this code?




Finally I've got another question: if
"str" => array ("n1"=>"fabio", "n2"=>"marcolino", "n3"=>"lauretta")
are saved in a database and I want to get them from it, is correct to write in the following way?

"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),


and to call them with Ajax:

... success:function(msg){
if(msg){
$("#location").html(Object.keys(msg.str).map(x => msg.str[x]).join(", "));
}else{
$("#location").html('Not Available');
}

Answer

Besides How can I show "fabio","marcolino","lauretta" using a loop for?

<?php 

$dati = array(
    "data" => array(
        'address_complete'=>$data->results[0]->formatted_address, 
        'address_square'=>$data->results[0]->address_components[1]->long_name,
        'location'=>$data->results[0]->address_components[2]->long_name,
        'postal_code'=>$data->results[0]->address_components[7]->long_name,
        'data_ora'=>$tmp_date
    ),
    "str" => array ("n1"=>"fabio",
                    "n2"=>"marcolino",
                    "n3"=>"lauretta")
);
?>

<script type="text/javascript">
<?="var p = " . json_encode($dati) ?>

// print individual elements
for (i in p.str) {
     console.log(p.str[i])
}

// print together
console.log(Object.keys(p.str).map(x => p.str[x]).join(", "))

</script>
Comments