我有两个有多行的表。我想将这两个表行组合成一个长数组,这个数组将被识别为一个数组 我写了这段代码
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row){
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
$data[] = $users_all;
}
echo json_encode($data);
它使重复数组不正确......
这就是我的结果显示
[{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
},
{
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}]
请帮我把它做成一个长阵列
我希望看到输出看起来像这样
{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}
答案 0 :(得分:2)
看看这个,我已经采用了示例值,它可以正常工作
$arr=array(array("abc"=>"1","def"=>"2"),array("abcc"=>"11","deff"=>"22"));
echo json_encode($arr);
$final = array();
foreach($arr as $item) {
$final = array_merge($final, $item);
}
print_r($final);
<强>输出强>
[{"abc":"1","def":"2"},{"abcc":"11","deff":"22"}]//json_array
Array ( [abc] => 1 [def] => 2 [abcc] => 11 [deff] => 22 )//final array
<强>更新强>
json_encode最终数组,你将获得所需的结果
echo json_encode($final);
输出
{"abc":"1","def":"2","abcc":"11","deff":"22"}
答案 1 :(得分:1)
未经测试:
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row) {
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
foreach($users_all as $user)
$data[] = $user;
}
}
echo json_encode($data);
// when you use json_decode use the 'true' flag as in
// $decodedJson = json_decode($json, true);
答案 2 :(得分:0)
在json_encode
之前合并它们:
$data[] = $posts_row;
$data2[] = $users_all;
$result = array_merge($data,$data2);
echo json_encode($result);