我正在开发一个IOS应用程序,对于API我将我的请求发送到一个应该用PHP返回JSON数据的URL 我很喜欢
[{"Child Care":"After Scool,Breakfast Club\n"},{"Child Care":"Breakfast Club"}]
但我希望得到像
[{
"Childcare":[
"All of Childcare",
"After school",
"Breakfast Club"
]}
我的代码是
<?php
session_start();
$connection=mysqli_connect('localhost','root','','testing') or die(mysqli_error());
$sql="select `Child Care` from Activity_type ";
$result = mysqli_query($connection,$sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray=array();
while($row =mysqli_fetch_assoc($result)){
array_push($emparray,$row);
}
header('Content-Type: application/json');
echo json_encode($emparray);
?>
答案 0 :(得分:3)
只需将其正确放入JSON
阵列即可。
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray['Child Care'][] = $row['Child Care'];
}
header('Content-Type: application/json');
echo json_encode($emparray);
从评论中回答你的第二个问题:
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
foreach($row as $key => $val) {
$emparray[$key][] = $val;
}
}
header('Content-Type: application/json');
echo json_encode($emparray);
答案 1 :(得分:1)
这将提供您想要的格式。让我知道这是否适合您。
while($row =mysqli_fetch_assoc($result)){
array_push($emparray,$row['Child Care']);
}
header('Content-Type: application/json');
echo json_encode(array("Childcare" => $emparray));
答案 2 :(得分:0)
尝试类似的事情,
$sql="select `Child Care` from Activity_type ";
$result = mysqli_query($connection,$sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray=array();
while($row =mysqli_fetch_assoc($result)){
$cares = explode(',' $row['Child Care']);
foreach($cares as $care){
$emparray[] = $care;
}
}
header('Content-Type: application/json');
echo json_encode($emparray);
使用php explode
功能