Return a JSON object using PHP json_encode() & MySQL to pass to jQuery function

五迷三道 提交于 2019-12-20 09:46:02

问题


I'm trying to create a json object from MySQL results, but not getting the result I need.

Here is the PHP

$json = array();
$result = mysqli_query ($connection, $query);
    echo '['; 

        while($row = mysqli_fetch_array ($result))     
        {
            echo '{';
            echo '"latitude":"'.$row['lat'].'",';
            echo '"longitude":"'.$row['lng'].'",';
            echo '"icon":'.'"./images/'.$row['busColor'].'.png"';
            echo '}';    
        }
        echo ']';

        $jsonstring = json_encode($json);
        echo $jsonstring;

        die(); 

It outputs this

[{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}][]

But I want this

[{"latitude":"39.976257","longitude":"-83.003464","icon":"./images/pink.png"}]

once I get the result I need to pass the object to a jQuery plugin function if that makes any difference

$.getJSON('myJsonURL, function(myMarkers){
  $("#map").goMap({
    markers: myMarkers
  });
});

Thanks


回答1:


I guess the correct way to do this would be:

$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))     
{
    $bus = array(
        'latitude' => $row['lat'],
        'longitude' => $row['lng'],
        'icon' => './images/' . $row['busColor'] . '.png'
    );
    array_push($json, $bus);
}

$jsonstring = json_encode($json);
echo $jsonstring;

die();



回答2:


you output your json by hand and then you call json_encode on an empty array() - $json

json_encode() outputs [] on you pass an empty array so your last [] comes from here
$jsonstring = json_encode($json);
echo $jsonstring;

Edit: More about json_encode json_encode php manual




回答3:


You start by defining an array.

You then generate some JSON manually.

You then convert the array to JSON and output it.

Replace all the echo statements in and at the edge of your while loop with code to generate an associative array containing the data, and then insert it into $json.



来源:https://stackoverflow.com/questions/4507366/return-a-json-object-using-php-json-encode-mysql-to-pass-to-jquery-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!