0

我有这两个数组,它们的 ID [3 和 4] 是常见的,ID [10] 是不同的。我只需要 ID 为 [10] 的商品

<?php

$usergroups = array();
$usergroups[] = array("id" => 3, "name" => "Parish 3");
$usergroups[] = array("id" => 4, "name" => "Parish 4");

$u= (object) $usergroups;
var_dump($u);


echo '<hr />';


$featuredgroups = array();
$featuredgroups [] = array("id" => 3, "name" => "Parish 3");
$featuredgroups [] = array("id" => 4, "name" => "Parish 4");
$featuredgroups [] = array("id" => 10, "name" => "Parish 10");

$fg = (object) $featuredgroups;
var_dump($fg);

  $filtered = array_diff($featuredgroups, $usergroups);
  var_dump($filtered); //returns empty result
?>

如何过滤掉用户的特色?我试过这个

$filtered = array();
foreach($u as $uu)
{
   $ug = (object) $uu;
   foreach($fg as $ff)
   {
      $fgr = (object) $ff;
      if($fgr->id != $ug->id)
         echo "<br>---".$fgr->name;  //am supposed to add this to filtered
   }
}

它正在打印出来

---Parish 4
---Parish 10
---Parish 3
---Parish 10

而不仅仅是'Parish 10',这是不同的。

更新

出于某种原因,array_diff如答案中所建议的那样不起作用。这仅适用于线性/一维数组。我用多维数组尝试过,就像问题中的那个一样,它没有用

  $filtered = array_diff($featuredgroups, $usergroups);
  var_dump($filtered); //returns empty result
4

3 回答 3

3

要获得两个数组的差异,您可以使用 array_diff。

http://php.net/manual/en/function.array-diff.php

$differences = array_diff($usergroups, $featuredgroups);
于 2012-11-02T18:46:55.337 回答
3

你需要使用array_diff,这是手册

于 2012-11-02T18:47:24.837 回答
1

让我们来看看这两个数组。

            $usergroups = array();
            $usergroups[] = array("id" => 3, "name" => "Parish 3");
            $usergroups[] = array("id" => 4, "name" => "Parish 4");

            $featuredgroups = array();
            $featuredgroups [] = array("id" => 3, "name" => "Parish 3");
            $featuredgroups [] = array("id" => 4, "name" => "Parish 4");
            $featuredgroups [] = array("id" => 10, "name" => "Parish 10");

现在,假设这是唯一的,我们可以在数组中id检索用户组中的所有s。id

foreach ($usergroups as $item => $value)
        {
            $c[] = $value['id'];
        }

这个 $c 数组将包含用户组中的所有ids。现在我们需要做的是,检查id特征组中是否存在;如果不存在,则检索这些值。这可以通过以下方式的组合foreach来完成:in_array()

foreach ($featuredgroups as $item => $value)
            {
                if (!in_array($value['id'], $c))
                {
                    $d[] = $value;
                }
            }

完整代码:

foreach ($usergroups as $item => $value)
            {
                $c[] = $value['id'];
            }

foreach ($featuredgroups as $item => $value)
            {
                if (!in_array($value['id'], $c))
                {
                    $d[] = $value;
                }
            }

这里$d将检索所需的结果。

于 2012-11-03T07:43:38.537 回答