Oj Obasi Oj Obasi - 2 months ago 9
PHP Question

I have this query that gives me the following php array data:

Here is the foreach loop to get data in an array.

foreach ($data['songsPlayList'] as $key => $value){
$data['playlistSongs'] = $this->_song->getSongsInPlaylist($value);
//var_dump($data['playlistSongs']);

}


If I view the source , I will see this :

array(1) {
[0]=>
array(8) {
["id"]=>
string(3) "121"
[0]=>
string(3) "121"
["artist"]=>
string(12) "2face Idibia"
[1]=>
string(12) "2face Idibia"
["song_title"]=>
string(13) "African Queen"
[2]=>
string(13) "African Queen"
["filename"]=>
string(30) "2face Idibia-African Queen.mp3"
[3]=>
string(30) "2face Idibia-African Queen.mp3"
}
}
array(1) {
[0]=>
array(8) {
["id"]=>
string(3) "493"
[0]=>
string(3) "493"
["artist"]=>
string(10) "Lucky Dube"
[1]=>
string(10) "Lucky Dube"
["song_title"]=>
string(11) "Remember Me"
[2]=>
string(11) "Remember Me"
["filename"]=>
string(26) "Lucky Dube-Remember Me.mp3"
[3]=>
string(26) "Lucky Dube-Remember Me.mp3"
}
}


With this, I can only print out the results one array. So what I want to do is convert it to an array like this :

array(437) {
[0]=>
array(12) {
["id"]=>
string(3) "121"
[0]=>
string(3) "121"
["artist"]=>
string(12) "2face Idibia"
[1]=>
string(12) "2face Idibia"
["song_title"]=>
string(13) "African Queen"
[2]=>
string(13) "African Queen"
["filename"]=>
string(30) "2face Idibia-African Queen.mp3"
[3]=>
string(30) "2face Idibia-African Queen.mp3"
}
[1]=>
array(12) {
["id"]=>
string(3) "493"
[0]=>
string(3) "493"
["artist"]=>
string(10) "Lucky Dube"
[1]=>
string(10) "Lucky Dube"
["song_title"]=>
string(11) "Remember Me"
[2]=>
string(11) "Remember Me"
["filename"]=>
string(26) "Lucky Dube-Remember Me.mp3"
[3]=>
string(26) "Lucky Dube-Remember Me.mp3"
}
}


So I can do a php foreach loop to get all the result data. Any suggestions?

Answer
$data['playlistSongs'] = [];
foreach ($data['songsPlayList'] as $key => $value){
  $data['playlistSongs'][] = $this->_song->getSongsInPlaylist($value);
}
var_dump($data['playlistSongs']);

other solution:

$data['playlistSongs'] = array_map(function($song) use($this) {
  return $this->_song->getSongsInPlaylist($song);
}, $data['songsPlayList']);