我怎么能在PHP中创建一个多维数组如下?

时间:2017-04-03 04:14:16

标签: php mysql sql arrays sorting

大家好我想创建一个多维数组作为下面的格式,但我正在努力这样做,任何帮助将不胜感激。谢谢。

    $movies = array();
    $sql = "SELECT u.username AS Username, group_concat(v.title) AS Video_title, group_concat(r.rate) AS Rating
    FROM `rating` AS r 
    JOIN `uploads` AS v ON r.video_id = v.vid_id 
    JOIN `users` as u ON u.user_id = r.rater_id 
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
    $movies[] = $result;
    }

    foreach($movies as $k => $v){
    unset($movies[$k]);
    $movies[$v['Username']] = $v;
    }
    foreach($movies as $k => $v){
    unset($movies[$k]['Username']);
    }

    print_r($movies);

这就是我目前所得到的:

     [user1] => Array ( [Video_title] => Snakes on the Plane,
                                         Superman Returns,
                                         The Night Listner,
                                         Lady in the Water,
                                         Just my Luck,
                                         You me and Dupree 
                         [Rating] => 3.5,
                                     3.5, 
                                     3,
                                     2.5,
                                     3,
                                     2.5 
                     ) )

但我的目标是按以下格式输出:

 'user1' => 
          array('Lady in the Water' => 2.5,
                'Snakes on a Plane' => 3.5, 
                'Just My Luck' => 3.0, 
                'Superman Returns' => 3.5,
                'You, Me and Dupree' => 2.5, 
                'The Night Listener' => 3.0
               )

3 个答案:

答案 0 :(得分:2)

更改以下行:

$movies[$v['Username']] = $v;

$movies[$v['Username']][] = $v;

然后再试一次。它将在每次迭代的Username索引下创建一个新数组。

答案 1 :(得分:1)

尝试使用此代码获取瞄准结果:

    $movies = array();
    $sql = "

    SELECT u.username AS Username, v.title AS Video_title, r.rate AS Rating
    FROM `rating` AS r 
    JOIN `uploads` AS v ON r.video_id = v.vid_id 
    JOIN `users` as u ON u.user_id = r.rater_id 
    GROUP by Username" ;

    $query = mysqli_query($conn, $sql);

    while($result = mysqli_fetch_assoc($query)){
        $movies[$result['Username']][$result['Video_title']] = $result['Rating'];
    }

    print_r($movies);

答案 2 :(得分:1)

你必须这样做: -

$trimmed_array_key=array_map('trim',$array_keys);

注意: -

这一行: - $compile

将执行以下操作: -

https://eval.in/766605

参考: - http://php.net/manual/en/function.array-combine.php