首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在php中合并数组中的另一个数组?

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

Stack Overflow用户
提问于 2018-06-20 23:33:14
回答 1查看 86关注 0票数 0

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

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

代码语言:javascript
复制
{"date":"2018-05-03","hour":"09:12:32","data":[null]}

它应该在'data'中返回第二个查询的结果

代码语言:javascript
复制
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}

PHP脚本:

代码语言:javascript
复制
$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);
EN

回答 1

Stack Overflow用户

发布于 2018-06-21 05:31:59

我不确定这是否是你想要实现的目标,因为你的描述很差,很难理解。

代码语言:javascript
复制
$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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50951966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档