PHP如何将MYSQL中SELECT出来的结果存入到已有数组中?

ybaby521 2015-06-29 07:44:58
叙述有点复杂,流程是这样的
1.需要按照JSON格式输出一串字符串,格式如下:
{
"list_info": [
{
"order_id": "1",
"order_status": "0",
"order_contact_type": "0",
"order_contact": "0",
"order_contact_name": "王二",
"order_contact_tel": "13386056143",
"cart_list": []
},
{
"order_id": "2",
"order_status": "0",
"order_contact_type": "0",
"order_contact": "5",
"order_contact_name": "李四",
"order_contact_tel": "18605449879",
"cart_list": []
}
],
"timestamp": "1435576540"
}
实现代码如下:

header("Content-type: text/html; charset=utf-8");

$user_id = $_POST['user_id'];

$rows = array();

$sql = "SELECT * FROM order_info WHERE order_info.user_id = '$user_id'";
$result = mysql_query($sql,$conn) or die(mysql_error());

while($r = mysql_fetch_assoc($result)) {
//cart_list 不在数据库搜索的结果中,所以人为预留cart_list
$r['cart_list'] = $tm;

$rows['list_info'][] = $r;

}
$rows['timestamp'] = time();

echo "<br />".JSON($rows);

2.php中调用数据库,select出来结果,如何保存到"cart_list"中?

$sqltmp = "SELECT * FROM order_goods_info WHERE order_goods_info.user_id = '$user_id' AND order_goods_info.order_id = '$order_id'";
$resulttmp = mysql_query($sqltmp,$conn) or die(mysql_error());
while($tmpr = mysql_fetch_assoc($resulttmp)){
//此时,如何将$tmpr 存储到第一步中的 cart_list 数组中去?

}


3.最终想达到的结果如下:
{
"list_info": [
{
"list_id": "10",
"list_status": "0",
"list_contact_type": "0",
"list_contact": "12345678",
"address_name": "北京天安门",
"address_tel": "010-1234-5678",
"address_person_name": "李刚",
"cart_list": [
{
"cloth_id": "1",
"count": "6",
"comment": "都要白色"
},
{
"cloth_id": "2",
"count": "5",
"comment": "要小号"
}
]
},
{
"list_id": "11",
"list_status": "1",
"customer_contact_type": "0",
"customer_contact": "12345678",
"address_name": "北京天安门",
"address_tel": "010-1234-5678",
"address_person_name": "李刚",
"cart_list": [
{
"cloth_id": "11",
"count": "6",
"comment": "都要白色"
},
{
"cloth_id": "12",
"count": "5",
"comment": "要小号"
}
]
}
],
"timestamp": "1234567890"
}

小白刚学习PHP,希望各位大神指教,在此谢过了
...全文
437 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
傲雪星枫 2015-06-30
  • 打赏
  • 举报
回复
建议一次查询,然后数组拼接。
xuzuning 2015-06-30
  • 打赏
  • 举报
回复
第一段的 $rows['list_info'][] = $r; 改写为
$rows['list_info'][$r['user_id']] = $r;
第二段写作
$rows['list_info'][$tmpr['user_id']]['cart_list'][] = $tmpr;
ohmygirl 2015-06-29
  • 打赏
  • 举报
回复
一次查询可以查出的记录,尽量不要多次去查询。
夏之冰雪 2015-06-29
  • 打赏
  • 举报
回复
通过表关联实现呢,不知道可以不。

21,892

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧