如何将平面MySQL数据转换为多维数组

时间:2015-05-12 01:01:01

标签: php multidimensional-array

我从MySQL SELECT查询中获取了这些数据......

+--------+----------+---------+--------------+----------------+
| vid_id | vid_name | file_id | file_url     | tag_name       |
+--------+----------+---------+--------------+----------------+
|      1 | Video 1  |       1 | video_1.mp4  | Lorem ipsum    |
|      1 | Video 1  |       2 | video_1.webm | Lorem ipsum    |
|      2 | Video 2  |       3 | video_2.mp4  | Dolor sit amet |
|      2 | Video 2  |       4 | video_2.webm | Dolor sit amet |
+--------+----------+---------+--------------+----------------+

...我试图进入这样的多维PHP数组:

Array
(
    [0] => Array
        (
            [name] => Video 1
            [tag] => Lorem ipsum
            [files] => Array
                (
                    [0] => video_1.mp4
                    [1] => video_1.webm
                )
        )

    [1] => Array
        (
            [name] => Video 2
            [tag] => Dolor sit amet
            [0] => Array
                (
                    [0] => video_2.mp4
                    [1] => video_2.webm
                )
        )
)

当我使用变量来检查视频名称是否已添加到数组时,我接近了。但是,我无法弄清楚如何在下一次迭代中仅将视频文件添加到嵌套数组中。到目前为止,这是我最好的尝试:

<?php
    // Define a variable to keep track of iterations:
    $title = '';

    while ($row = mysqli_fetch_assoc($r)) {

        if ($title != $row['vid_name']) {
            // Grab all the data:
            $video_data[] = array(
                'name' => $row['vid_name'],
                'tag' => $row['tag_name'],
                $files = array(
                    'file' => $row['file_url']
                )
            );
        } else {
            // Grab only the file URL and add it to the files array:
            $files[] = $row['file_url'];
        }

        // Update the tracking variable:
        $title = $row['vid_name'];
    }
?>

这不起作用:

Array
(
    [0] => Array
        (
            [name] => Video 1
            [tag] => Lorem ipsum
            [0] => Array
                (
                    [file] => video_1.mp4
                )
        )

    [1] => Array
        (
            [name] => Video 2
            [tag] => Dolor sit amet 
            [0] => Array
                (
                    [file] => video_2.mp4
                )
        )
)

我确信我想要实现的目标是可行的,但我没有足够的PHP知识来解决这个问题(我怀疑有更好的方法来获取阵列我想要)。建议和指示非常感谢!

1 个答案:

答案 0 :(得分:3)

为什么不使用vid_id或vid_name(如果唯一)作为第一个数组键?

检查数组中是否存在vid_id,如果没有,请添加详细信息,并在该密钥下添加与该vid_id相对应的每个文件。

$video_data = array();
while ($row = mysqli_fetch_assoc($r)) {

    $key = $row['vid_id'];

    // Add details if they don't exist yet
    if (!isset($video_data[$key])) {
        $video_data[$key] = [
            'name' => $row['vid_name'],
             'tag' => $row['tag_name']
        ];
    }
    // Always add file
    $video_data[$key]['files'][] = $row['file_url'];
}