gpt4 book ai didi

php - 一个对象 json 中的两个查询 mysql

转载 作者:行者123 更新时间:2023-11-29 08:25:58 25 4
gpt4 key购买 nike

我有两个表,我想将它们转换为 json,如下所示:

[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]

但是我的代码的结果是这样的:

[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]

代码为数组“people”创建了一个新对象,我希望它们位于同一个对象中

$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");

$json = array();
$json2['people'] = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}

while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];

array_push($json2['people'],$row_temp);
}

array_push($json, $json2);

echo Json_encode($json);

如何使数组与表“数据”位于同一对象中?

非常感谢

最佳答案

我想你可以试试这个

$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");

// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);

$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);

print_r($json) 的结果应该是这样的

Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)

[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)

)

)

echo json_encode($json) 的结果应该是

{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}

如果你执行echo json_encode(array($json)),那么你将把整个json包装在一个数组中,就像这样

[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]

关于php - 一个对象 json 中的两个查询 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com