Jump to content

Adding New Rows To Associative Arrays


billf2007

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.