1

I tried to get a formatter json from mysql, but I dont know how can get it.

$query = 'SELECT data1,data2,data3,data4 FROM database';
$dbquery = mysql_query($query);
$geojson = array();

while($row = mysql_fetch_assoc($dbquery)) {
    $feature = array('loc' => $row['data1'],$row['data2'],'title' => $row['data3'], $row['data4']);
    array_push($geojson,$feature);
};

echo json_encode($geojson);

This outputs:

[{"loc":data1,"0":data2,"title":"data3","1":"data4"},
{"loc":data1,"0":data2,"title":"data3","1":"data4"}]

I want this instead:

[{"loc":[data1,data2], "title":"data3 data4"},
{"loc":[data1,data2], "title":"data3 data4"}]

What should I change in my code?

3 Answers 3

2

Try this query and see if it gives you the output that you need

        SELECT
    CONCAT('[', 
            GROUP_CONCAT('
                  CONCAT('{"loc": [', data1, data2, '], ')
                , CONCAT('"title": "', data3, data4 ,'"}')
                )
, ']')
        FROM database

you can also do something like this

SELECT
  CONCAT(data1,data2) AS loc
, CONCAT(data3,data4) as title 
FROM database';

Then in PHP you can do this

$feature = array(array('loc'=> $row['loc'],
                 'title' => $row['title']));
echo json_encode($feature);
Sign up to request clarification or add additional context in comments.

Comments

1

Your loop is not correct it should have been:

while($row = mysql_fetch_assoc($dbquery)) {
    $feature = array('loc' => array(
                              $row['data1'],$row['data2']
                              ),
                     'title' => $row['data3'] .' '.$row['data4']
                );
    array_push($geojson,$feature);
};

Comments

1

You should change your $feature line like this:

$feature = array('loc' => array($row['data1'], $row['data2']),'title' => $row['data3'].' '.$row['data4']);

That will result in a json blob like the following, for each line:

{"loc":["data1","data2"],"title":"data3 data4"}

Explanation

  • loc: You want an array. So you have do define it with array() in PHP. If you want to cast the value to numbers, just typecast them if needed:

    array((float)$row['data1'], (float)$row['data2'])

  • title: Just concatenate the two strings with dots and a space in-between.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.