我有一个像这样的
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
$ret[]=$thv;
}
这里我把$thv
的每个输出都像$ret[]=$thv;
一样推到$ret
$ret
的输出为,
[1] => Array
(
[0] => 701
[id] => 701
[1] => 1180
[media_image_id] => 1180
[2] => George Cumming - Session 1
[name] => George Cumming - Session 1
[3] =>
[preparation] =>
[4] =>
[description] =>
[5] =>
[coaching_points] =>
[6] =>
[progressions] =>
)
[2] => Array
(
[0] => 701
[id] => 701
[1] => 1180
[media_image_id] => 1180
[2] => George Cumming - Session 1
[name] => George Cumming - Session 1
[3] =>
[preparation] =>
[4] =>
[description] =>
[5] =>
[coaching_points] =>
[6] =>
[progressions] =>
)
这里id=>701
重复,所以我想做的是,从数组中删除重复的值,但在foreach循环内。如,
if(id=>701 NOT EXIST IN $ret)
{
$ret[]=$thv;
}
这样就不需要再创建一个foreach了。有人知道如何在php中做到这一点吗?
我有一个想法-使用id
作为$ret
的关键。例子:
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
if (!isset($ret[$thv['id']])){
$ret[$thv['id']]=$thv;
}
}
如果你仍然想要0..n作为$ret
的键,你可以这样做:
$ret = array_values($ret);
$ret = array();
$ids = array();
foreach($temp as $k => $v) {
// Run query
$thv = mysql_fetch_array(mysql_query(" SOMEQUERY "));
// Check if id present
if (!in_array($thv['id'], $ids)) {
// Not present, add to arrays
$ids[] = $thv['id'];
$ret[] = $thv;
}
}
试试这段代码。
$ret=array();
foreach($temp as $k=>$v)
{
$temp =array_column($ret,'id');
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
if(!in_array($thv['id'],$temp)){
$ret[]=$thv;
}
}