Hi guys i am trying to create a multi dimensional array as the format bellow but i am struggling to do so, any help would be appreciated. Thank you.
$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);
This is what i am currently getting:
[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
) )
But i am aiming to output it in the following format:
'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
)
You have to do it like below:-
$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;
}
$new_movies = array(); // a new array variable
foreach($movies as $k => $v){
$array_keys = explode(',',$v['Video_title']); // explode Video_title string into array
$trimmed_array_key=array_map('trim',$array_keys); // trim all spaces from each value of $trimmed_array_key array
$array_values = explode(',',$v['Rating']); // explode Rating array
$trimmed_array_values=array_map('trim',$array_values);//remove all spaces from $trimmed_array_values array
$new_movies[$v['Username']] = array_combine($trimmed_array_key,$trimmed_array_values); // combine $trimmed_array_key array and $trimmed_array_values array and assign to corresponding user
}
echo "<pre/>";print_r($new_movies); // print new array
Note:-
This line:-$trimmed_array_key=array_map('trim',$array_keys);
Will do something like below:-
reference:- http://php.net/manual/en/function.array-combine.php
Change the following line:
$movies[$v['Username']] = $v;
to
$movies[$v['Username']][] = $v;
and try again. It will create a new array under Username
index for each iteration.
Try this code for your aiming result:
$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);