Array Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Array Question

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Post 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));
                              
                                                                          }
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You'll have to combine the results.
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Post 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?
mentor
Forum Contributor
Posts: 100
Joined: Sun Mar 11, 2007 11:10 am
Location: Pakistan

Post 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));
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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.
Post Reply