获取多行并以 JSON 格式显示

fetching multiple rows and display in json

提问人:Mary Reejo R 提问时间:4/25/2020 最后编辑:Alessio CantarellaMary Reejo R 更新时间:4/25/2020 访问量:145

问:

我有一个PHP代码,如下所示:

while ($row2 = mysqli_fetch_assoc($check2)) {
  // $leadarray[] = $row2;
  $service_id[$i] = $row2['service_id'];
  $row1['service_id'][$i] = $service_id[$i];
  $service_name[$i] = $row2['service_name'];
  $row1['service_name'][$i] = $service_name[$i];
  $i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);

获得类似

{
  "leaddetails": [
    {
      "service_id": [
        "7",
        "2"
      ],
      "service_name": [
        "Past Control Services",
        "Civil Finishing"
      ],
    }
  ]
}

我想要这样的输出:

"service_id": [
  1:  "7",
  2: "2"
],
"service_name": [
  1: "Past Control Services",
  2: "Civil Finishing"
],

[
  "service_id":  "7",
  "service_name": "Past Control Services",
  "service_id":  "2",
  "service_name": "Civil Finishing",
]
php json mysqli

评论

1赞 Barmar 4/25/2020
第二种选择是不可能的,数组不能有重复的键。
0赞 Mary Reejo R 4/25/2020
[ “service_id1”: “7”, “service_name1”: “过去的控制服务”, “service_id2”: “2”, “service_name2”: “土木装修”, ] 这个选项是否可行?
0赞 Mary Reejo R 4/25/2020
如何为此输出编写代码?
0赞 u_mulder 4/25/2020
添加这 1、2 有什么意义?它与 0、1 相同。

答:

0赞 Jeroen van der Laan 4/25/2020 #1

$trimmed1在将它传递给(PHP 中的关联数组)时被视为对象,因为您显式地给它一个键(在 JSON 中被视为对象属性):json_encode

$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';

这将导致编码到一个对象中:json_encode$trimmed1

{
   "leaddetails": "foobar"
}

要获得所需的结果,请在传递给 时被视为 ARRAY。$trimmed1json_encode

$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
0赞 wayan edi 4/25/2020 #2

第二种选择是不可能的 你可以像这样做[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]

评论

0赞 wayan edi 4/25/2020
使用类 ex:class Data{ $service_id; $service_name; } $obj = new Array(); while ($row2 = mysqli_fetch_assoc($check2)){ $data = new Data(); $data->service_id = $row2['service_id']; $data->service_name = $row2['service_name']; array_push($obj, $data); } echo json_encode($obj);
0赞 David Buck 4/25/2020
请编辑您的答案以添加格式正确的 bove 代码。
0赞 wayan edi 4/25/2020 #3
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]

像这样使用类

class Data{ 
  $service_id; 
  $service_name; 
} 

$obj = new Array(); 
while ($row2 = mysqli_fetch_assoc($check2)){ 
  $data = new Data(); 
  $data->service_id = $row2['service_id']; 
  $data->service_name = $row2['service_name']; 
  array_push($obj, $data); 
} 
echo json_encode($obj);

评论

0赞 Mary Reejo R 4/29/2020
这段代码是哎呀,你能帮我把这段代码转换为过程编程吗?
0赞 Barmar 4/25/2020 #4

首先创建二维数组。然后在循环期间推送到嵌套数组上。

$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
    $result["service_id"][] = $row["service_id"];
    $result["service_name"][] = $row["service_name"];
}
echo json_encode($result);