2017-05-25 72 views
1

这是我的代码:的MySQL结果在一个JSON对象

$query = "select ((recipients.maennlichDeutsch+recipients.maennlichAuslaender+recipients.weiblichDeutsch+recipients.weiblichAuslaender)/inhab.Einwohner) as Sozialhilfeempfaenger from recipients left join education on recipients.Bundesland = education.FK_Land and recipients.Jahr = education.FK_Jahr left join inhab on recipients.Bundesland = inhab.FK_land and recipients.Jahr = inhab.FK_Jahr where recipients.Bundesland in ('Thueringen') and education.Abschluss in ('Hauptschulabschluss')"; 
$result=mysqli_query($db, $query) or die('Error querying database.'); 
$data = array(); 
while($row =mysqli_fetch_assoc($result)) 
{ 
    $data[] = $row; 
} 
echo json_encode($data); 
?> 

,这是JSON结果我得到:

[  
    { 
     "Sozialhilfeempfaenger": "0.0208" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0202" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0198" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0209" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0222" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0235" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0254" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0031" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0032" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0036" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0038" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0037" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0037" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0039" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0039" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0042" 
    },  
    { 
     "Sozialhilfeempfaenger": "0.0044" 
    } 
] 

我有什么做的,存放这样说?

{ 
    "sozialhilfeempfaenger": [0.0039, 0.0042...] 

} 
+0

你尝试过什么比获取数据等? – CodeGodie

回答

3

只要改变它,你推容器内的阵列的方式。只需直接选择索引,然后将其推入数组中。

理念:

$data['sozialhilfeempfaenger'] = array(); // initialize 
while ($row = mysqli_fetch_assoc($result)) { 
    $data['sozialhilfeempfaenger'][] = $row['Sozialhilfeempfaenger']; 
             //^directly access the index 
} 
echo json_encode($data); 
1
$query = "select ((recipients.maennlichDeutsch+recipients.maennlichAuslaender+recipients.weiblichDeutsch+recipients.weiblichAuslaender)/inhab.Einwohner) as Sozialhilfeempfaenger from recipients left join education on recipients.Bundesland = education.FK_Land and recipients.Jahr = education.FK_Jahr left join inhab on recipients.Bundesland = inhab.FK_land and recipients.Jahr = inhab.FK_Jahr where recipients.Bundesland in ('Thueringen') and education.Abschluss in ('Hauptschulabschluss')"; 
$result=mysqli_query($db, $query) or die('Error querying database.'); 
$data = array(); 
while($row =mysqli_fetch_assoc($result)) 
{ 
    $data[] = $row['Sozialhilfeempfaenger']; 
} 
echo json_encode(array('Sozialhilfeempfaenger' => $data)); 
?>