我从mysql中获取数据,如...
$query = "SELECT legal_country, count(*) FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
目前的结果是:
[{"legal_country":"US","count(*)":"107865"},{"legal_country":"DE","count(*)":"44711"},{"legal_country":"SL","count(*)":"1"}]
然而,我的目标是让json字符串像:
{"map": "worldLow", "areas": [{"id": "US","value": "107865"},{"id": "DE","value": "44711"},{"id": "SL","value": "1"}]}
如何在数组之前添加{“map”:“worldLow”,“areas”:....}以及如何更换标签legal_country - > id和count(*) - >价值?
此外,这是一个带有'echo'的工作示例......但是我需要'return'功能......
$prefix = '';
echo '{"map": "worldLow", "areas": [';
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "id": "' . $row['legal_country'] . '",' . "\n";
echo ' "value": "' . $row['count(*)'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]}";
echo的工作示例如下所示:
{"map": "worldLow", "areas": [ {
"id": "US",
"value": "107865"
},
{
"id": "DE",
"value": "44711"
},
{
"id": "SL",
"value": "1"
}
]}
答案 0 :(得分:0)
在使用$data
json_encode
$query = "SELECT legal_country as `id`, count(*) as `value` FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$json= array();
$area = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$area[] = $row;
}
$data = array(
'map' => 'worldlow',
'area' => $area,
);
return json_encode( $data );
答案 1 :(得分:0)
根据您的要求创建一个包含结果的数组。
$query = "SELECT legal_country AS `id`, count(*) AS `value`
FROM accounts
GROUP BY legal_country
ORDER BY count(*) DESC";
$dataArr = $areasArr = array();
if ($result = mysql_query( $query )) {
while ( $row = mysql_fetch_assoc( $result ) ) {
$areasArr[] = $row;
}
$dataArr = array(
"map" => "worldLow",
"areas" => $areasArr
);
}
return json_encode( $dataArr, true );
还使用mysqli_*
个函数代替mysql_*