如何使用PHP以正确的格式获取JSON数据

然后库玛

我正在开发一个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); 

    ?>
达伦

只需将其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); 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章