Как я могу сформировать два массива для одного объекта массива? - PullRequest
1 голос
/ 21 февраля 2011

У меня есть два массива $ 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 голос
/ 21 февраля 2011

Хорошо, это решит вашу проблему:

// 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...