fog*_*bit 2 php arrays comparison
这里是C++/Python的人.
我需要比较两个php-arrays containsig用户定义的类.
class Point
{
var $x;
var $y;
function _construct($x_, $y_)
{
$this -> x = $x_;
$this -> y = $y_;
}
}
$mas1 = array(new Point(0,1),new Point(0,1),new Point(0,1));
$mas2 = array(new Point(0,1),new Point(0,1),new Point(0,1));
if (array_diff($mas1,$mas2) == array())
{
echo "they're equal\n";
}
Run Code Online (Sandbox Code Playgroud)
我得到了"可捕获的致命错误:类Point的对象无法转换为字符串".当我试图使用简单
if ($mas1 == $mas2)
Run Code Online (Sandbox Code Playgroud)
我弄错了.
问题:1)有没有办法为我的类重载比较运算符点2)如何正确比较包含用户定义类的两个数组?
谢谢.
我用php 5.2.11
实际上,PHP不支持重载运算符.第一个比较仅测试字符串数组,而第二个比较测试对象的内部编号而不测试其内容.
你应该在这里做的是使用函数array_udiff.
此函数允许您使用回调函数比较两个数组.在此回调函数中,您可以包含所需的逻辑.此函数返回两个数组之间的差异数组.如果要检查两者是否相等,请查看返回的数组是否为空.看到array_udiff()
请参阅以下示例:
class Point
{
var $x;
var $y;
function _construct($x_, $y_)
{
$this -> x = $x_;
$this -> y = $y_;
}
static function compare(Point $a, Point $b)
{
// Do your logic here.
if ($a->x === $b->x && $a->x === $b->x) {
return 0;
}
return ($a->x > $b->x)? 1:-1;
}
}
$mas1 = array(new Point(0,1),new Point(0,1),new Point(0,1));
$mas2 = array(new Point(0,1),new Point(0,1),new Point(0,1));
if(count(array_udiff($mas1, $mas2, 'Point::compare')) == 0) {
// Eq
}
else {
// Diff
}
Run Code Online (Sandbox Code Playgroud)