假设我在表中有一组行,并且每行都有一个名为city的列,并为其分配了一些值 iam迭代结果集,我需要将每行的城市值列表分配给一个唯一的数组
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)
}
答案 0 :(得分:3)
您正在为循环的每一行重置$cities
到一个新数组。更好的是:
$cities = array();
foreach ($res as $row)
{
if ( ! in_array($row['city'], $cities)) {
$cities[] = $row['city'];
}
}
答案 1 :(得分:2)
你应该在foreach循环之前$cities =array();
。现在你在每次迭代时擦除数组。
此致 阿林
答案 2 :(得分:2)
$cities
变量。SELECT DISTINCT city FROM ...
)答案 3 :(得分:1)
例如:
$cities =array();
foreach($res as $row){
$cities[] = $row['city'];
}
var_dump($cities);
但是,这取决于$res
答案 4 :(得分:1)
使用键消除重复:
$cities = array();
foreach($res as $row)
$cities[$row['city']] = true;
$cities = array_keys($cities);