如何在PHP中更改对象中JSON数组的输出?

时间:2017-04-19 04:59:55

标签: php arrays json api

我有关于API JSON输出的问题。我在循环中遇到JSON输出,当我强制将数组格式转换为索引数组时,它正在创建自己的索引。

PHP代码:

$sql = "SELECT name,fname,address FROM user_management";
$array = array();

$result = $conn->query($sql);
$i=1;

if ($result->num_rows > 0) {
    // output data of each row
    $array=["message"=>"success"];
    while($row = $result->fetch_assoc()) {

    $array[] = ["Hello" => $row];

 } 

} 
else 
{
    echo "0 results";
}
 //echo implode(',', $array);
 // Take output array glue it with the
echo json_encode($array);
$conn->close();
?>

我收到的回复是:

{
  "message": "success",
  "0": {
    "Hello": {
      "name": "harjot",
      "fname": "tejinder",
      "address": "noida"
    }
  },
  "1": {
    "Hello": {
      "name": "regret",
      "fname": "egegrregeger",
      "address": "gegreg"
    }
  },
  "2": {
    "Hello": {
      "name": "harjot1",
      "fname": "harjot2",
      "address": "noida"
    }
  },
  "3": {
    "Hello": {
      "name": "har",
      "fname": "har1",
      "address": "Punjab"
    }
  }
}

我希望响应没有数组自己制作的0,1,2,3。有没有办法访问数组的索引?

预期输出:

{   "message": "success",
    "Hello": {
      "name": "harjot",
      "fname": "tejinder",
      "address": "noida"   },
    "Hello1": {
      "name": "regret",
      "fname": "egegrregeger",
      "address": "gegreg"   },
    "Hello2": {
      "name": "harjot1",
      "fname": "harjot2",
      "address": "noida"   },
    "Hello3": {
      "name": "har",
      "fname": "har1",
      "address": "Punjab"
    }   
}

3 个答案:

答案 0 :(得分:0)

您已声明$i维持计数器,但您没有使用它。

更改此内容:

$array[] = ["Hello" => $row];

:此:

$array["Hello".$i] = $row;

同时添加$i++;以维护和增加计数器值。

PHP代码:

<?php //
$sql = "SELECT name,fname,address FROM user_management";
$array = array();

$result = $conn->query($sql);
$i=1;

if ($result->num_rows > 0) {
    // output data of each row
    $array=["message"=>"success"];
    while($row = $result->fetch_assoc()) {

    $array["Hello".$i] = $row;//added line here
    $i++;//added this line to increment counter everytime.
 } 

} 
else 
{
    echo "0 results";
}
 //echo implode(',', $array);
 // Take output array glue it with the
echo json_encode($array);
$conn->close();
?>

答案 1 :(得分:0)

试试这个。

$i = 0;
while($row = $result->fetch_assoc()) {

    $array["Hello".$i++] = $row;

 } 

OR

$i = 0;
while($row = $result->fetch_assoc()) {

    $array["Hello".$i] = $row;
    $i++;
 } 

答案 2 :(得分:0)

试试这个

if ($result->num_rows > 0) {
    // output data of each row
    $array=["message"=>"success"];
    $index = "";
    while($row = $result->fetch_assoc()) {
        $array["Hello" . $index] = $row;
        $index = $index ? ($index + 1) : 1;
    }
}