遵循比较函数:
function compareCollections($c1, $c2) {
// If the colletions have different sizes we return false:
if (count($c1) != count($c2)) {
return false;
}
// The collections have the same size, we check element by element:
foreach($c1 as $item) {
// We find the current element in $c1 in $c2:
$itemToCompare = array_filter($c2, function ($compareItem) use ($item) {
return ($compareItem['id'] == $item['id']);
});
// If we did not find the element in $c2, the collections are different:
if (empty($itemToCompare)) {
return false;
}
$itemToCompare = current($itemToCompare);
// We now use PHP to check the element keys:
$diff = array_diff_key($item, $itemToCompare);
// If there is a different, return false:
if (!empty($diff)) {
return false;
}
}
// If everything is ok until here, the collections are the same:
return true;
}
还有一个测试:
$collection1 = [
['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],
['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 800],
];
$collection2 = [
['id' => 1, 'name'=> 'phone', 'quantity' => 1, 'price' => 1200],
['id' => 2, 'name'=> 'tv', 'quantity' => 3, 'price' => 400],
];
$collection3 = [
['id' => 1, 'name'=> 'tv', 'quantity' => 1, 'price' => 1200],
['id' => 2, 'name'=> 'tv', 'quantity' => 3],
];
var_dump(compareCollections($collection1, $collection2)); // true
var_dump(compareCollections($collection1, $collection3)); // false