如何比较同一个数组中的对象?

时间:2013-03-08 19:37:07

标签: php arrays

第一个数组有一些元素,其中p2p_id为value。

array (size=5)
  0 => 70 
  1 => 99
  ...

通过查询上面的p2p_ids,我得到第二个数组,每个元素都是一个带有详细信息的对象。我想比较这些元素,找到具有相同p2p_to值的元素,以及相同的p2p_type。我想学习如何。

array (size=5)
  0 => 
    object(stdClass)[234]
      public 'p2p_id' => string '70' 
      public 'p2p_from' => string '1124'
      public 'p2p_to' => string '1459' 
      public 'p2p_type' => string 'd_to_x'
  1 => 
    object(stdClass)[237]
      public 'p2p_id' => string '99' 
      public 'p2p_from' => string '1327' 
      public 'p2p_to' => string '1459' 
      public 'p2p_type' => string 'd_to_x'
  2=>
  3=>
  4=>
  5=>
  ...

1 个答案:

答案 0 :(得分:0)

<?php
class Post
{
    public $p2p_id, $p2p_from, $p2p_to, $p2p_type;

    /**
     * @param posts  Array   Post objects to compare with this post object
     */
    public function findMatchingPosts($posts){
        $results = array();
        foreach($posts as $post){
            if($post->p2p_to == $this->p2p_to && $post->p2p_type == $this->p2p_type){
                $results[] = $post;         
            }
        }
        return $results;
    }
}
相关问题