开发者

How do i create the array with the values being fetched from database in php

开发者 https://www.devze.com 2023-01-19 03:32 出处:网络
Say i am having set of rows in a table and each row is having a column called citywithsome values assigned to it

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开发者_JAVA技巧 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)
     }


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'];
    }
}


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

Regards, Alin


  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 ...)


For example:

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

However it depends on the content of $res


Using keys to eliminate duplicates:

$cities = array();
foreach($res as $row)
  $cities[$row['city']] = true;
$cities = array_keys($cities);
0

精彩评论

暂无评论...
验证码 换一张
取 消