BobNat BobNat - 1 month ago 11
PHP Question

add an element to multidimensionnal array in a loop

$arr1[] = "Bob Marley";
$arr1[] = "Album1";
$arr1[][] = Song1;


0 => string 'Bob Marley'
1 => string 'Album1'
2 =>
0 => string 'Song1'


I have the array above and want to add a new song in a loop, I want

0 => string 'Bob Marley'
1 => string 'Album1'
2 =>
0 => string 'Song1'
1 => string 'Song2'


I have an array with albums (attr: name, artist, and an array of songs), my code look like the following.

foreach ($AlbumsArray as $album) {
if(preg_match("#".$regexx."#i", $album->getArtist()) || preg_match("#".$regexx."#i", $album->getTitle())){
$arrayAlbumFound[] = $album->getArtist();
$arrayAlbumFound[] = $album->getTitle();
$albumFound = true;
}
foreach ($album->getSongsArray() as $songs) {
if(preg_match("#".$regexx."#i", $songs->getName())){
if($albumFound){
$arrayAlbumFound[][count($arrayAlbumFound] = array($songs->getName());
}
else{
$arrayAlbumFound[] = $album->getArtist();
$arrayAlbumFound[] = $album->getTitle();
$arrayAlbumFound[count($arrayAlbumFound][] = $songs->getName();
$albumFound = true;
}
}
}
$albumFound = false;

Answer

Use a separate variable for collecting the songs, and do it before storing the found album artist and title, so you know whether there are matching songs first:

foreach ($AlbumsArray as $album) { 
    $songsFound = [];
    foreach ($album->getSongsArray() as $songs) {
        if(preg_match("#".$regexx."#i", $songs->getName())){
            $songsFound[] = $songs->getName();
        }
    }
    if(count($songsFound) ||
            preg_match("#".$regexx."#i", $album->getArtist()) || 
            preg_match("#".$regexx."#i", $album->getTitle())){
        $arrayAlbumFound[] = $album->getArtist();
        $arrayAlbumFound[] = $album->getTitle();
        if (count($songsFound)) {
            $arrayAlbumFound[] = $songsFound;
        }
    }
}