dongyupan4850 2015-04-23 13:47
浏览 90
已采纳

PHP:使用array_merge的foreach循环来创建json对象

I'm new to php but i really like like it so far! Now i stumbled over a problem with array_merge.

This is my code, it simply grabs each table specified in my database then makes it to a big json file.:

  $tables = array("buildings", "medical", "other", "tools", "traps", "weapons"); 

    foreach ($tables as $table) {

        // Get tables from database
        $sth = $db->query("SELECT * FROM $table");
        $result = $sth->fetchAll();

        // Merge arrays together
        if ($arr === null) {
            //echo "its 0 <br/> ";
            $arr = array( "$table" => $result );
        } else {
            //echo "more than 0 <br/> ";
            $arr2 = array( "$table" => $result );
            $merge = array_merge($arr, $arr2);
        }

    } //End loop

    echo $merge;

So far It's working somehow, I manage to get the first table "buildings" and the last table "weapons" to be displayed the way i want perfectly!

But I don't understand why it jumps over the other ones.. I believe it has something to do with $arr2 and that i need to specify a unique array for each of the tables. But how can i achieve this? Is this the way to go or is there a more efficient way to achieve this? Thanks!

  • 写回答

5条回答 默认 最新

  • dongliao8069 2015-04-23 13:55
    关注

    Its failing because of this line

        $merge = array_merge($arr, $arr2);
    

    Your merge is always a merge of $arr (which is the first entry in $tables) and $arr2, which is the latest entry being processed. You are not merging the data with the previously merged data, such as

        $arr = array_merge($arr, $arr2)
    

    Also, you can get rid of the if/else logic by just starting off by setting $arr to an empty array to start.

        $arr = array();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据