Page 1 of 1

Array Question

Posted: Wed Mar 14, 2007 10:04 am
by thiscatis
I'm getting all the names from a database table "users" in the column username

so i'm getting the array

Code: Select all

$users = array(0 => 'john', 1 => 'simon', 2 => 'john');
But how do I get from that array to an array that counts the equal items and then puts it like item => quantity

Code: Select all

$newarray = array('john' => '2' , 'simon'=> '1' );
is this possible?

Posted: Wed Mar 14, 2007 10:12 am
by feyd

Posted: Wed Mar 14, 2007 10:27 am
by thiscatis
Ok, I got that right..
I'm now trying to do that with multiple tag words in a row.
But it just gives the count array per row and starts again for the next instead of a global view on the results.

code:

Code: Select all

$result = mysql_query("SELECT m_tags FROM users ") or die(mysql_error());

      while($row = mysql_fetch_array($result)) {

                  $m_tags = $row['m_tags'];
                  $tagged = explode(",", $m_tags);

                  print_r(array_count_values($tagged));
                              
                                                                          }

Posted: Wed Mar 14, 2007 10:48 am
by feyd
You'll have to combine the results.

Posted: Wed Mar 14, 2007 11:04 am
by thiscatis
Hmm, I put a for loop in the while statement to add the results to a specified array but it just loops the same array x-times and moves on to the next row
I do need to place a for loop with array_merge in there or how would you do it?

Posted: Wed Mar 14, 2007 11:27 am
by mentor
try this one

Code: Select all

$result = mysql_query("SELECT m_tags FROM users ") or die(mysql_error()); 
$tagged = array();
while($row = mysql_fetch_array($result)) { 
	$m_tags = $row['m_tags']; 
	$tagged = array_merge($tagged, explode(",", $m_tags)); 
}
print_r(array_count_values($tagged));

Posted: Thu Mar 15, 2007 5:00 am
by stereofrog
thiscatis, the problem you have here arises from the wrong database design. Instead of storing a bunch of comma separated values in one column, use a secondary table and JOINs.