Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 662
JCam Avatar asked Dec 22 '10 08:12

JCam


2 Answers

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();
like image 51
RabidFire Avatar answered Oct 19 '22 22:10

RabidFire


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

like image 45
cristian Avatar answered Oct 19 '22 23:10

cristian