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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟