手动json_encode语法错误

时间:2017-07-12 10:26:02

标签: php

我的代码如下:

 $db = mysqli_connect("localhost", "root", "", "vieuxparis1");
 $mn = mysqli_query($db, 'SELECT * FROM paris');
 $jsonval = array();
 while($get = mysqli_fetch_assoc($mn)):
 $json = array();
 $json["id"] = $get["ID"];
 $json["picture"] = $get["picture"];
 $json["name"] = $get["name"];
 $json["category"] = $get["category"];
 $json["address"] = $get["adress"];
 $json["about"] = $get["about"];
 $json["location"]=array(
     "latitude" => $get["latitude"],
     "longitude" => $get["longitude"]
       );
 $json["tags"]=array(
   "in",
   "aliqua",
   "voluptate"
 );
 $json["openings"]=array(
   "monday" => "10:00 - 22:00",
   "tuesday"=> "09:00 - 21:00",
   "wednesday"=> "09:00 - 21:00",
   "thursday"=> "09:00 - 21:00",
   "friday"=> "09:00 - 21:00",
   "saturday"=> "09:00 - 21:00",
   "sunday"=> "closed"
 );
 array_push($jsonval,$json);
 endwhile;

所以,当我回声时,我得到了这个,有两次"纬度"和经度":

"about":"Ceci est un quartier parisien","latitude":"48.8405818","longitude":"2.286173299999973","location":["48.8405818","2.286173299999973"],

我想要这个:

"about": "Ceci est un quartier parisien",
"location": {"latitude": "48.861001",
             "longitude": "2.335876"
            },

你知道我应该怎么写我的代码吗?

2 个答案:

答案 0 :(得分:2)

您正在以错误的方式构建阵列。您没有设置关联键,它只是一个赋值:

$json = array(
$json["latitude"] = $get["latitude"]
)

使用“=>”设置关联键的正确方法符号:

$array = array(
    'key' => 'value'
);

// or

$array['key'] = 'value';

请尝试:

$json["about"] = $get["about"];
$json["location"]=array(
   "latitude" => $get["latitude"],
   "longitude" => $get["longitude"]
);

答案 1 :(得分:1)

您需要使用数组表示法=>而不是= ASSIGNMENT operator

$json["location"]=array(
   "latitude" => $get["latitude"],
   "longitude" => $get["longitude"]
);