使用php输入Json对象的元素

时间:2016-07-23 11:31:49

标签: arrays json

我有以下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循环显示marcolinolaurettafor

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');
        }

1 个答案:

答案 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>