在循环中检查数组键和值是否存在

时间:2015-07-14 07:35:51

标签: php arrays multidimensional-array foreach

我有一个这样的foreach

Option Explicit
Public Sub Autoserial()

  Dim iRowStart As Long
  Dim iRowEnd As Long
  Dim iCol As Long, iRow as long
  Dim iIncrement As Long

  iRowkStart = Selection.Row
  iRowEnd  = Selection.Rows.Count + Selection.Row - 1
  iCol = Selection.Column
  iIncrement = 1

  For iRow  =iRowStart to iRowEnd
    Cells(iRow, iCol).Value = iIncrement
    iIncrement  = iIncrement  + 1
  Next iRow

End Sub

此处我将$ret=array(); foreach($temp as $k=>$v) { $thv=mysql_fetch_array(mysql_query(" SOMEQUERY ")); $ret[]=$thv; } 的每个输出推送到$thv,如$ret$ret[]=$thv;的输出是,

$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] => ) 重复,所以我想要做的是,从数组中移除重复值但在该foreach循环中。 像,

id=>701

所以这样就不需要创造另一个foreach了。任何人都知道如何在PHP中执行此操作?

3 个答案:

答案 0 :(得分:3)

我的想法 - 使用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);

答案 1 :(得分:0)

$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;
    }
}

答案 2 :(得分:0)

试试这段代码。

$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;
    }

}