tags:

views:

46

answers:

5

Say i am having set of rows in a table and each row is having a column called city with some values assigned to it iam iterating through the result set and i need to assign the list of city values of each row in to an array only unique

     foreach($res as $row){
       $cities =array();
       $cities[] = $row['city'];
       //when i say 
       var_dump($cities);
       //Iam not able to get array .how do i do that 
       $maincities = array('A','B',C)
     }
+3  A: 

You're resetting $cities to a new array for each row you loop through. Better would be:

$cities = array();
foreach ($res as $row)
{
    if ( ! in_array($row['city'], $cities)) {
        $cities[] = $row['city'];
    }
}
chigley
@chigley:iam getting null array when i try to compare the cities array with main city array if ( !in_array($row['city'], $mainarray)) { echo "one"; $cities[] = $row['city']; } var_dump($cities)
Someone
@some: Why do you use `$mainarray` when the answer states `$cities`? Sound more like mixing up variables (especially the NULL part...)
Wrikken
@Someone - you'll need to post up your full code if you want any more help. We're not here to guess! My answer will work when used correctly! What is `$maincities` compared to `$cities`?
chigley
+2  A: 

Hi,

You should but $cities =array();before the foreach loop. Now you are erasing the array at each iteration.

Regards, Alin

Alin Purcaru
+2  A: 
  1. You empty the $cities variable every time in the loop.
  2. It is probably a lot better practise to only have unique cities in your resultset (SELECT DISTINCT city FROM ...)
Wrikken
Erm, care to explain the downvote / where I went wrong?
Wrikken
Apparently not...
Wrikken
+1  A: 

For example:

$cities =array();
foreach($res as $row){      
   $cities[] = $row['city'];       
}
var_dump($cities);

However it depends on the content of $res

erenon
+1  A: 

Using keys to eliminate duplicates:

$cities = array();
foreach($res as $row)
  $cities[$row['city']] = true;
$cities = array_keys($cities);
konforce
it should be done at database level
Col. Shrapnel
I agree. But some times you may need the non-distinct data as well, and you'd have to run a second query to get the distinct values. Example: If building a faceted search, you might want to display all of the results, along with a checkbox for each distinct city, category, etc, found within that resultset.
konforce