duankao4489 2015-02-01 12:12
浏览 15
已采纳

如何对两个数组使用array_diff

I have a PHP class and want to compare the data using two arrays according like the code below.

But, here I want to show out the difference data of both arrays.

I have tried the code below but it is not working and I'm stuck of this.

<?php
class TestClass{
    public $fool = 'hehe';
    public $fool2 = 'huhu';
    public $fool3 = 'haha';
    public $fool4 = 'haha';

    public function __toString()
    {
        return $this->fool;
        return $this->fool2;
        return $this->fool3;
        return $this->fool4;

    }

}


$arr1 = array();
$class = new TestClass;
$class ->fool='one day';
$class ->fool2 ='test';
array_push($arr1,$class);

$arr2 = array();
$class2 = new TestClass;
$class2 ->fool ='one day';
$class2 ->fool2 ='different test';
array_push($arr2,$class2);

echo print_r($arr1).'<br/>';
echo print_r($arr2).'<br/>';
$result=array_diff($arr1,$arr2);
print_r($result);



?>
  • 写回答

1条回答 默认 最新

  • dra8603 2015-02-01 13:31
    关注

    You are mixing things too much, just to fix your code even if I disagree with your goal and way you do that:

    class TestClass{
        public $fool = 'hehe';
        public $fool2 = 'huhu';
        public $fool3 = 'haha';
        public $fool4 = 'haha';
    
        public function __toString()
        {
            return '1: '.$this->fool.'; 2: '.$this->fool2.'; 3: '.$this->fool3.'; 4: '.$this->fool4;
        }
    
        public function asArray()
        {
            return array($this->fool, $this->fool2,$this->fool3,$this->fool4);
        }
    }
    
    $arr1 = array();
    $class = new TestClass;
    $class ->fool='one day';
    $class ->fool2 ='test';
    $arr1[]=$class;
    
    $arr2 = array();
    $class2 = new TestClass;
    $class2 ->fool ='one day';
    $class2 ->fool2 ='different test';
    $arr2[] = $class2;
    
    echo $arr1[0]."
    ";
    echo $arr2[0];
    print_r($result);
    
    $result=array_diff($arr1[0]->asArray(),$arr2[0]->asArray());
    
    print_r($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试