I'm looking for a fast way to get the subset of 2 arrays containing the same kind of objects using PHP functions.
I'm looking for the red part:
class Order { private $_orderId; private $_someOtherAttributes; }
I'm currently using array_uintersect()
to get the intersection and array_udiff()
to get rid of the intersection.
$array_1 = array($o1, $o2, $o3 ... $on); $array_2 = array($o1, $o2, $o3 ... $on); function order_hash($object) { return sprintf('%d', $object->getOrderId()); } function compare_objects($a, $b) { return strcmp(order_hash($a), order_hash($b)); } $intersection = array_uintersect($array_1, $array_2, 'compare_objects'); $subset = array_udiff($array_2, $intersection, 'compare_objects');
Is there a faster / more efficient way? I need to work with a lot of objects > 400 each array and very often as well.
I'm currently using PHP Version 7.1.4.
My changes:
I changed the Order-Class to:
class Order { public $_orderId; private $_someOtherAttributes; }
and compare_objects()
to:
function compare_objects($a, $b) { if($a->_orderId> $b->_orderId) { return 1; } else if($a->_orderId< $b->_orderId) { return -1; } return 0; }
and using array_udiff($array_1, $array_2, 'compare_objects')
instead off array_udiff($array_2, array_udiff($array_1, $array_2, 'compare_objects'), 'compare_objects')
I'm aware that public attributes aren't the best practice, but changing it this way I gained 300% more speed.
compare_objects()
you see object context ($this
) being used. This doesn't make sense. Iforder_hash()
andcompare_objects()
ofOrder
class, why not show code for whole class for review? Right now it is hard to understand why you even put theOrder
class code in here.\$\endgroup\$$subset = array_udiff($array_2, $array1, 'compare_objects');
. Any object not in$array2
will just be skipped. However, this question looks to be off-topic here, since we want the real code and not just some dumbed-down minimal version (in contrast to Stack Overflow).\$\endgroup\$