如何在php中的另一个数组中合并一个数组?

时间:2018-06-20 15:33:14

标签: php arrays array-merge

我正在尝试将一个名为'$rows_ban'的数组合并或放置在另一个名为'$rows'的最终数组中的另一个数组(称为'$rows_final')的子项中。

我正在使用array_merge,但在'data'内部返回null:

{"date":"2018-05-03","hour":"09:12:32","data":[null]}

它应该返回'data'内第二个查询的结果:

{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}

PHP脚本:

$rows = array();
$rows_ban = array();
$rows_final= array();

$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");

while($r = mysqli_fetch_array($result1)) {
    $rows['date']= $r[2];
    $rows['hour']= $r[3];
    $rows['data'][]= null;
}

$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );

while($r = mysqli_fetch_array($result2)) {
    $rows_ban['cod'] = $r[0];
    $rows_ban['name'] = $r[1];
    $rows_ban['total'] = $r[2];

    $result3 = mysqli_query($link,"SELECT *, 1 as Filter from 
        table3 where cod=".$r[0]." order by dates desc");

    while($r = mysqli_fetch_assoc($result3)) {
        $rows_ban['sub_data'][] = $r;
    }

    $rows_final = array_merge($rows['data'],$rows_ban);
    // here im trying to merge the $rows_ban array inside the 
    $rows['data']
}

echo json_encode($rows_final);

1 个答案:

答案 0 :(得分:0)

由于描述很差且难以理解,因此不确定是否要完成此操作。

$output = [];
$tmpRows = [];

$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');

if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $output['date'] = $tmp[0]['sync_date'];
    $output['time'] = $tmp[0]['sync_time'];
}

$result = mysqli_query($link, 'SELECT cod, name, total from totals ');

if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $tmpRows['cod'] = $tmp[0]['cod'];
    $tmpRows['name'] = $tmp[0]['name'];
    $tmpRows['total'] = $tmp[0]['total'];

    $result = mysqli_query($link,"SELECT *, 1 as Filter from 
        table3 where cod={$tmp[0]['cod']} order by dates desc");

    if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $tmpRows['sub_data'] = $tmp[0];
    }

    $output['data'] = $tmpRows;
}


print_r(json_encode($output));

array_merge也不像您认为的那样工作。它像名称状态一样返回合并的数组。关于您的代码,最终结果将完全是$ rows_ban编码为json。

http://php.net/manual/en/function.array-merge.php