billf2007 Posted February 6, 2007 Share Posted February 6, 2007 I am trying to create an array that contains a genre of music and a count. I'd like the genre to be the index, and the value associated with it to be the number of instances of that genre occur in one's library. Essentially, something like this: Rock =>10 Reggae => 5 Metal => 6 Folk => 2 Here's my code: $genreArr = array(); $myLib = new dbMusicLibrary(); $myLib->query("SELECT * FROM `MusicLibrary` WHERE `user_id` ='".$id."'"); while($myLib->fetch()) { $songid = $myLib->song_id; if ($songid!=0) { $song = dbSong::staticGet($songid); $genre = $song->getGenres(); //Name Of Genre (e.g. "Rock", "Reggae" etc. if (array_key_exists($genre1, $genreArr)) { $genreArr[$genre] += 1; } else { $genreArr[] = array($genre1=>0); } } } The problem is that the array has a numerical index rather than the genre name. Here's the output Array ( [0] => Array ( [Pop] => 0 ) [1] => Array ( [Rock] => 0 ) [2] => Array ( [Rock] => 0 ) [3] => Array ( [Rock] => 0 ) [4] => Array ( [Hip Hop] => 0 ) [5] => Array ( [Rock] => 0 ) [6] => Array ( [Pop] => 0 ) [7] => Array ( [Folk] => 0 ) [8] => Array ( [Rock] => 0 ) [9] => Array ( [Rock] => 0 ) [10] => Array ( [Rock] => 0 ) [11] => Array ( [Electronic] => 0 ) [12] => Array ( [Electronic] => 0 ) Link to comment https://forums.phpfreaks.com/topic/37247-adding-new-rows-to-associative-arrays/ Share on other sites More sharing options...
kenrbnsn Posted February 6, 2007 Share Posted February 6, 2007 Change this line: <?php $genreArr[] = array($genre1=>0); ?> to <?php $genreArr[$genre1] = 0; ?> Ken Link to comment https://forums.phpfreaks.com/topic/37247-adding-new-rows-to-associative-arrays/#findComment-177902 Share on other sites More sharing options...
billf2007 Posted February 6, 2007 Author Share Posted February 6, 2007 ha, wow. huge oversight on my part. thanks! Link to comment https://forums.phpfreaks.com/topic/37247-adding-new-rows-to-associative-arrays/#findComment-177904 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.