Json_encode一个合并的数组,但只返回1行

时间:2018-08-03 10:05:16

标签: php mysql

这是我的代码,获取我需要的查询结果

$json_array = array();
$sql = "call rep_info();";
$result = $connect->query($sql);
while ($row = $result->fetch_assoc()) {
  $json_array[] = $row;
}

mysqli_free_result($result);  
mysqli_next_result($connect); 

// Buat info user
$json_array2 = array();
$sql = "call rep_user();";

$result = $connect->query($sql);
while ($row = $result->fetch_assoc()) {
  $json_array2[]["user"] = $row;
}

然后我像这样将两个数组合并为一个

$timeline = array_merge($json_array[0],$json_array2[0]);
$timeline2 = array_merge($json_array[1],$json_array2[1]);

$timeline = array_merge($timeline,$timeline2);

编码合并后的数组以及回显变量

$encoded = json_encode($timeline);

echo $encoded;

所以基本上我想要显示的是查询结果的两行,它们来自json_array [0]和json_array [1]。但是我在json_array [1]和json_array2 [1]的回显结果中只得到1行。

这段代码有什么问题?谢谢!

编辑:

print_r($json_array[0]);
print_r($json_array2[0]);

Array
(
    [id] => 11087
    [message] => Late post.\nDarmo ramai lancar
    [latitude] => -7.292500019073486
    [longitude] => 112.7388916015625
    [image] => 1529894809620.jpeg
    [thumb] => 
    [sub_category] => 
    [is_need_respond] => 0
    [is_sticky] => 0
    [is_hidden] => 0
    [viewed] => 18
    [deleted_at] => 
    [created_at] => 2018-06-25 02:48:04
)
Array
(
    [user] => Array
        (
            [id] => 621
            [name] => asd
            [username] => asd
            [verified] => 2
            [avatar] => icfab.jpg
            [level] => 10
        )

)

1 个答案:

答案 0 :(得分:0)

尝试这样

$timeline = $json_array[0];
$timeline['user'] = $json_array2[0]['user'];
$timeline2 = $json_array[1];
$timeline2['user'] = $json_array2[1]['user'];

$timeline = [$timeline, $timeline2];

$encoded = json_encode($timeline);

echo $encoded;

编辑

假设$json_array$json_array2的长度相同,则可以像这样合并它们

foreach($json_array as $idx => &$item)
{
  $item['user'] = &$json_array2[$idx]['user'];
}
echo json_encode($json_array);

更新

我不确定您为什么不理解这个1行周期。我会尽力解释它。

您有两个长度相同的数组-$json_array$json_array2。 您遍历$json_array中的每个元素,并查看$json_array2中相同的数组索引。当两个数组中都有对应的元素时,只需将第二个数组中的user键复制到第一个数组中即可。