【问题标题】:How to get JSON data in Correct format using PHP如何使用 PHP 获取正确格式的 JSON 数据
【发布时间】:2016-03-30 13:56:18
【问题描述】:

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

    ?>

【问题讨论】:

  • 在这里发布你得到的东西
  • [{"Child Care":"After Scool,Breakfast Club\n"},{"Child Care":"Breakfast Club"}]

标签: php mysql json


【解决方案1】:

只需将其正确放入您的JSON 数组即可。

$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
    $emparray['Child Care'][] = $row['Child Care'];
}

header('Content-Type: application/json');
echo json_encode($emparray); 

回答 cmets 提出的第二个问题:

$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); 

【讨论】:

  • 快乐伙伴@SaiKumar
  • 如果我有 7 个像 'Childcare' 这样的列,我该怎么办@Darren
  • 您希望数据如何传递?
  • 我在一个表中有 7 列我想得到像 [{ "Childcare":[ "All of Childcare", "After school",] "Classes":[ "All of Classes", "产前”,].........}
  • 你知道了 tnq @darren
【解决方案2】:

这将提供您想要的格式。让我知道这是否适合您。

while($row =mysqli_fetch_assoc($result)){
    array_push($emparray,$row['Child Care']);
}   
header('Content-Type: application/json');
echo json_encode(array("Childcare" => $emparray)); 

【讨论】:

  • 不会出现 Notice 之类的错误:9 行 C:\xampp\htdocs\activitytype.php 中的未定义偏移量:0
    {"育儿":[null,null]}
【解决方案3】:

试试类似的,

$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); 

使用phpexplode函数

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多