我有以下json对象:
$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;
如何输入n1
元素以显示fabio
作为输出?
$p.str.n1
不起作用。我怎么能这样做?
此外,如何使用fabio
循环显示marcolino
,lauretta
,for
?
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];
}
如何修复此代码?
最后我还有另一个问题:如果"str" => array ("n1"=>"fabio", "n2"=>"marcolino", "n3"=>"lauretta")
保存在数据库中并且我想从中获取它们,那么以下列方式编写是否正确?
"str" => array("n".$i=>"Ti sei incrociato con ".$array_db[username]),
并用Ajax调用它们:
... success:function(msg){
if(msg){
$("#location").html(Object.keys(msg.str).map(x => msg.str[x]).join(", "));
}else{
$("#location").html('Not Available');
}
答案 0 :(得分:1)
此外,我如何使用循环显示“fabio”,“marcolino”,“lauretta” 为?
<?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>