我是PHP的新手。我想在数组的每个对象中添加数组。它是数组内部的数组,每个数组对象都包含一个数组。我也在互联网上搜索我没有找到与此相关的任何内容。
这是我的愿望json
[{
"id":1,
"name":"Grey",
"list":[
{
"id":1,
"name":"60 X 60 ABC"
},
{
"id":2,
"name":"40 X 40 PQR"
},
{
"id":3,
"name":"45 X 45 XYZ"
}
]
},
{
"id":2,
"name":"Yarn",
"list":[
{
"id":4,
"name":"YARN ABC"
},
{
"id":5,
"name":"YARN XYZ"
}
]
}]
所有这些数据都是从mysql数据库中填充的。
这是我的PHP代码
$sql = "select * from tblType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$obj = new stdClass;
$obj->id = $rows["id"];
$obj->name = $rows["name"];
$obj->list = $array2;
$sql2 = "select * from tblQuality where typeId = $obj->id";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$obj2 = new stdClass;
$obj2->id = $row["id"];
$obj2->name = $row["name"];
array_push($array2, $obj2);
}
}
array_push($array, $obj);
}
}
echo json_encode($array);
mysqli_close($conn);
我不知道如何在数组中添加数组。请帮忙。
答案 0 :(得分:1)
试试这个:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$sql = "select * from tblType";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$obj = new stdClass;
$obj->id = $rows["id"];
$obj->name = $rows["name"];
$obj->list = array();
$sql2 = "select * from tblQuality where typeId = $obj->id";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$obj2 = new stdClass;
$obj2->id = $row["id"];
$obj2->name = $row["name"];
array_push( $obj->list, $obj2);
}
}
array_push($array, $obj);
}
}
echo json_encode($array);
mysqli_close($conn);
答案 1 :(得分:1)
你在这里:
$sql = "select * from tblType";
$result = $conn->query($sql);
$results = [];
if ($result->num_rows > 0) {
while($rows = $result->fetch_assoc()) {
$item = [];
$item['id'] = $rows['id']
$item['name'] = $rows['name'];
$item['list'] = [];
$sql2 = "select * from tblQuality where typeId = " . $rows['id'];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$item['list'][] = [
'id' => $row['id'],
'name' => $row['name']
]
}
}
$results[] = $item
}
}
echo json_encode($results);
mysqli_close($conn);
提示:不要将stdClass
个对象用作数组。他们不是故意的。