duan88014
duan88014
2014-05-16 12:42
浏览 494

为json选择查询多维数组

I'm really stuck and don't know how to tackle this: I'd like to query my MySQL database so I have a multidimensional associative Array of selected tables.
This array is my goal:

$ar = Array(
    table1name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),
    table2name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),
    table3name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),

);

So if I encode it with json_encode($ar), the result should look like this:

{
    "table1name": [
        {
            "field1": "a",
            "field2": "b",
        },
    {
            "field1": "c",
            "field2": "d"
    }
    ],
    "table2name": [
        {
            "fieldx": "1",
            "fieldy": "2",
        },
        {
            "fieldx": "3",
            "fieldy": "4"
        }
    ],
    "table3name": [
        {
            "fieldz": "1",
            "fieldq": "2",
        },
        {
            "fieldz": "3",
            "fieldq": "4"
        }
    ]
}

This is what I have so far but does not lead to expected results:

function tablesToJson()
{
    $mysqli = new mysqli("localhost", "user", "password", "test");
    $tables = Array();
    array_push($tables, "table1name");
    array_push($tables, "table2name");
    $finalArray = Array();

    foreach ($tables as $table) {
        if ($result = $mysqli->query('SELECT * FROM ' . $table)) {

            $rows = Array();
            while ($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            array_push($finalArray, $rows);
        }
    }
    return $finalArray;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanlie4621
    duanlie4621 2014-05-16 13:04
    已采纳

    you forgot/missed to use a key when adding the table results to your final array. So instead of

    array_push($finalArray, $rows);
    

    You should use something like:

    $finalArray[$table] = $rows;
    

    So you set a new key>element combination to your finalResult, having $table as a key as you requested.

    function tablesToJson()
    {
        $mysqli = new mysqli("localhost", "user", "password", "test");
        $tables = Array();
        array_push($tables, "table1name");
        array_push($tables, "table2name");
        $finalArray = Array();
    
        foreach ($tables as $table) {
            if ($result = $mysqli->query('SELECT * FROM ' . $table)) {
    
                $rows = Array();
                while ($row = $result->fetch_assoc()) {
                    $rows[] = $row;
                }
                $finalArray[$table] = $rows;
            }
        }
        return $finalArray;
    }
    
    点赞 评论

相关推荐