Reputation: 1057
I have one foreach like this
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
$ret[]=$thv;
}
Here im pushing every output of $thv
to $ret
like $ret[]=$thv;
and output of $ret
is,
[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] =>
)
Here id=>701
repeating, so what i want to do is, remove duplicate values from array but within that foreach loop.
Like,
if(id=>701 NOT EXIST IN $ret)
{
$ret[]=$thv;
}
SO that way no need to create another foreach. Anyone have idea how to do this in php?
Upvotes: 0
Views: 1835
Reputation: 1356
Try this code.
$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;
}
}
Upvotes: 0
Reputation: 721
I've an idea - use the id
as the key of $ret
. Example:
$ret=array();
foreach($temp as $k=>$v)
{
$thv=mysql_fetch_array(mysql_query(" SOMEQUERY "));
if (!isset($ret[$thv['id']])){
$ret[$thv['id']]=$thv;
}
}
If you still want 0..n to be the keys of $ret
, you can do like this:
$ret = array_values($ret);
Upvotes: 3
Reputation: 14863
$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;
}
}
Upvotes: 0