多维数组无需重复

时间:2016-01-03 00:37:54

标签: php mysql arrays multidimensional-array pdo

我有两个MySQL表,一个名为"版本"另一个被称为" line"在一个名为" project"。

的数据库中

"版本"表包括:

id (PRIMARY / AI) = int
version           = string

行:

# | version
------------
0 | 100
1 | 200
3 | 400

" line"表包括:

id (PRIMARY / AI) = int
lines             = string
version_id        = string (ID from table version)

行:

# | line     | version_id
--------------------------
0 | line #1  | 0
1 | line #2  | 0
2 | line #3  | 1
3 | line #4  | 0
4 | line #5  | 1  

如何创建多维数组以输出示例JSON(伪)

"full" =>
    "version" => "100"
        "id"    => "0", (version id table)
        "line"  =>
            "row_0" => "line #1", (from lines table)
            "row_1" => "line #2",
            "row_2" => "line #4",
    "version" => "200"
        "id" => "1",
        "line" =>
            "row_0" => "line #3",
            "row_1" => "line #5",
    "version" => "300"
        "id" => "3",
        "line" => "EMPTY" (no lines for this version)
]

我重写了几次代码,但我无法使其正常工作。无论是我卡住还是我完成了无限循环的错误。这就是我现在所得到的:

function returnJson() {
    $db = DB::query("SELECT * FROM version");

    foreach ($db as $row) {
        $i++;
        $lines = DB::Query("SELECT * FROM lines WHERE version_id=%i", $row['id']);

        // approach to nested array?
    }
}  

我正在使用MeekroDB,因此任何MySQL方法都会被抵消。如果您对PDO更熟悉,可以在PDO中编写示例。

2 个答案:

答案 0 :(得分:1)

我假设你想要的数组在php中看起来像这样:

SELECT v.id AS versionId, v.version l.id as linesId, l.lines
FROM version v
INNER JOIN lines l ON v.id = l.version_id

使用JOIN

$versions = array();

foreach($db as $row) {
  if (!isset($versions[$db["version"]]))
    $versions[$db["version"]] = array (
      "versionId" =>  $db["versionId"],
      "line" => array()
    );
  if (!empty($db["lines"]))
    $versions[$db["version"]][lines"][] = $db["lines"];
}

然后是一个带有一些if语句的循环来构建数组

connection = new SqlConnection(@"Data Source=(localdb)\mssqllocaldb;Initial Catalog=dbNotes;Integrated Security=True;MultipleActiveResultSets=true");
        categoriesUI1.tvwCategories.SelectedNode = categoriesUI1.tvwCategories.TopNode;
        int count = categoriesUI1.Categories.Count;

        if (count > 0)
        {
            for (int i = count; i > 0; i = count)
            {
                categoriesUI1.Categories.RemoveAt(0);
                count = categoriesUI1.Categories.Count;
            }
        }

        connection.Open();
        SqlCommand commandNote = new SqlCommand("SELECT ID, Cat_ID, Titel, Text, Created FROM tblNote WHERE Titel LIKE '%" + searchBarUI1.getTextValue() + "%'", connection);
        SqlDataReader readerNote = commandNote.ExecuteReader();
        if (readerNote.HasRows)
        {
            Category category = new Category();
            while (readerNote.Read())
            {
                int id = readerNote.GetInt32(0);
                int Cat_id = readerNote.GetInt32(1);
                string title = readerNote.GetString(2);
                string text = readerNote.GetString(3);
                DateTime created = readerNote.GetDateTime(4);
                string Cat_title = "";

                SqlCommand commandCategory = new SqlCommand("SELECT Titel FROM tblCategory WHERE ID = " + Cat_id, connection);
                SqlDataReader readerCategory = commandCategory.ExecuteReader();
                if (readerCategory.HasRows)
                {
                    while (readerCategory.Read())
                    {
                        Cat_title = readerCategory.GetString(0);
                        category = new Category(Cat_id, Cat_title);
                    }
                }
                Note note;
                note = new Note(id, title, text, created);
                category.Notes.Add(note);
                readerCategory.Close();
                categoriesUI1.Categories.Add(category);
            }

        }
        readerNote.Close();
        connection.Close();

答案 1 :(得分:0)

在此SO post中尝试接受的答案,该答案也会处理嵌套的JSON数据。

此外,您可能希望将SQL减少到下面,只需使用一个循环而不是上面的SO帖子中的两个嵌套循环。

SELECT *
  FROM version
 INNER 
  JOIN lines
    ON version.id = lines.version_id

希望这有帮助。