3

I have 2 PHP arrays, a simple one:

array
  0 => int 5
  1 => int 6

and an array of objects:

array
  0 => 
    object(stdClass)[43]
      public 'id' => int 1
  1 => 
    object(stdClass)[46]
      public 'id' => int 3
  2 => 
    object(stdClass)[43]
      public 'id' => int 5
  3 => 
    object(stdClass)[46]
      public 'id' => int 6
  4 => 
    object(stdClass)[46]
      public 'id' => int 7

I'd like to make a diff of these 2 arrays to eliminate in the second those present in the first. In this example, i don't want the ids 5 and 6 in the second array. But i need help ;>

Thank you.

fabien

4

4 回答 4

3

你可以试试 :

$diff = array_diff(array_map(function ($v) {
    return $v->id;
}, $array2), $array1);

观看现场演示

于 2013-05-22T10:52:13.543 回答
3

假设$objects是您的对象数组,并且$values是您要删除的值数组...

foreach如果要返回对象,可以使用循环:

$values = array(5, 6);
$objects = array(
    (object) array("id" => 1),
    (object) array("id" => 3),
    (object) array("id" => 5),
    (object) array("id" => 6),
    (object) array("id" => 7)
);
foreach($objects as $key => $object) {
    if(in_array($object->id,$values)) {
        unset($objects[$key]);
    }
}

现场演示(0.008 秒)

如果您想使用diff函数本身(这可能但很尴尬,可读性较差,并且只会返回一个值数组),您可以(如 Baba 建议的那样)返回id内联对象的 :

$values = array(5, 6);
$objects = array(
    (object) array("id" => 1),
    (object) array("id" => 3),
    (object) array("id" => 5),
    (object) array("id" => 6),
    (object) array("id" => 7)
);
$diff = array_diff(array_map(function ($object) {
    return $object->id;
}, $objects), $values);

现场演示(0.008 秒)

于 2013-05-22T10:53:26.843 回答
2

循环第二个数组并使用in_array方法首先检查现有值

$firstArray = array(5, 6);
foreach ($objects as $key => $object) {
    if (in_array($object->id, $firstArray)) {
        unset($objects[$key];
    }
}
于 2013-05-22T10:50:49.193 回答
1

对于早于 5.3 的版本

 foreach( $arr_2nd as $key => $val  )
{
   $arr_2nd[$key] = $val->id;
}

array_diff( $arr_1st, $arr_2nd );
于 2013-05-22T10:59:12.960 回答