我无法在PHP中创建多维数组

时间:2014-01-03 20:25:32

标签: php arrays multidimensional-array

我正在尝试编写一些可以在页面左侧列出艺术家的PHP代码(成功)
但是我没有使用那些艺术家来找到他们的歌曲并显示在页面的右侧。 歌曲名称的格式如下:“(艺术家) - (歌曲).mp3”
继承我的代码:

<?php
// integer starts at 0 before counting
$dir = 'songs/';
$i = 0;
$artistExplode = array();
if ($handle = opendir($dir)) {
$artists = array();
while (($file = readdir($handle)) !== false){
    if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
        $artistExplode[$i] = explode(" - ",$file);
        $artist = @$artistExplode[$i][0];
        if(!in_array($artist, $artists)) {
            $artists[$i] = $artist;
            $i++;
        }
}
}
$x = $i;
$i = 0;
$songs = 0;
while($x !== 1){
$i++;
$songs++;
if($handle = opendir($dir)) {
    while(($file = readdir($handle)) !== false) {
        if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
            //echo $file."<hr />";
            $songs++;
            $artists[$i][$songs] = $file;
        }
    }
}
    $artists[$i];
$x--;
}
print_r($artists);

我做了一些研究并且不明白数组中的随机字符是如何产生的,我希望每个艺术家的歌曲名称都在一个子数组中

这是print_r()的输出

Array ( [0] => [1] => 2 2DEEHKMTTT [2] => DVBBS & Borge2DEEHKMTTT [3] => Eminem 2DEEHKMTTT [4] => Hardwell & Dyro 2DEEHKMTTT [5] => Kanye West & Jay Z 2DEEHKMTTT [6] => Martin Garrix 2DEEHKMTTT [7] => TryHardNinja 2DEEHKMTTT )

2 个答案:

答案 0 :(得分:1)

我会这样做(未经测试):

<?php
// integer starts at 0 before counting
$dir = 'songs/';
$i = 0;
$artistExplode = array();
if ($handle = opendir($dir)) {
$artists = array();
while (($file = readdir($handle)) !== false){
    if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
        $artistExplode = explode(" - ",$file);
        $artist = (string)trim($artistExplode[0]);
        $song=(string)trim($artistExplode[1]);

        if($artist<>'' && $song<>'') {
            $artists[$artist][]=$song;
        }
    }
}
}
print_r($artists);
?>

答案 1 :(得分:1)

我做了以下测试:

        $music[] = "Eminem - Survival.mp3";
        $music[] = "Eminem - Survival2.mp3";
        $music[] = "Eminem - Survival3.mp3";
        $music[] = "Eminem - Survival4.mp3";
        $music[] = "Jay Z - Song.mp3";
        $music[] = "Jay Z - Song1.mp3";
        $music[] = "Jay Z - Song2.mp3";

        foreach($music as $mus)
        {
            $artist[] = explode("-",$mus);

        }

        $test = "Eminem";
        echo "Eminem Songs"."</br>";
        foreach($artist as $art)
        { 
          if(trim($art[0])==$test)
          {
              echo $art[1]."</br>";
          }
        }

        $test = "Jay Z";
        echo "Jay Z Songs"."</br>";
        foreach($artist as $art)
        { 
          if(trim($art[0])==$test)
          {
              echo $art[1]."</br>";
          }
        }

在这里工作小提琴:http://phpfiddle.org/main/code/n90-3td