如何将两个数组组成一个数组对象?

时间:2011-02-21 10:40:54

标签: php multidimensional-array

我有两个数组$ A(对象数组)和$ B

  $A = 
  Array
  (
  [0] => objval Object
      (

      [id_groupe] => 51
      )

  [1] => objval Object
      (

      [id_groupe] => 46
      )

  [2] => objval Object
      (
      [id_groupe] => 52
      )

  )


  $B = 
  Array(51,46)

如果id_groupe $A $B Array ( [0] => objval Object ( [id_groupe] => 52 ) ) 中存在{{1}},那么我希望返回新的结果,这样就可以得到如此结果:

{{1}}

任何可以帮助我?

1 个答案:

答案 0 :(得分:1)

好的,这将解决您的问题:

// object class
class xy{

    public $id_groupe = 0;

    function xy($id_groupe){
        $this->id_groupe = $id_groupe;
    }


}

// initialize test case Array A
$A = array();
$A[] = new xy(51);
$A[] = new xy(46);
$A[] = new xy(52);

// initialize test case Array B
$B = array(46,51);

// init result array
$diff = array();

// Loop through all elements of the first array
foreach($A as $elem)
{
  // Loop through all elements of the second loop
  // If any matches to the current element are found,
  // they skip that element
  foreach($B as $elem2)
  {
    if($elem->id_groupe == $elem2) continue 2;
  }
  // If no matches were found, append it to $diff
  $diff[] = $elem;
}

// test Array
print_r($diff);