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

后端 未结 3 1138
攒了一身酷
攒了一身酷 2021-02-02 04:16

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 = m         


        
相关标签:
3条回答
  • 2021-02-02 04:53

    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();
    
    0 讨论(0)
  • 2021-02-02 04:57

    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

    0 讨论(0)
  • 2021-02-02 05:02

    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.

    0 讨论(0)
提交回复
热议问题