Hello i have two arrays one coming from the client and the other coming from my database, i want to be able to compare these two arrays and make sure they are both equal.
你好,我有两个数组一个来自客户端,另一个来自我的数据库,我希望能够比较这两个数组,并确保它们是相等的。
By equal i mean they both have the same keys and the keys have the same values:
相同的意思是他们都有相同的键,键具有相同的值:
array (size=2)
0 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 100
1 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 200
array (size=2)
0 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 100
1 =>
array (size=5)
'id' => int 13
'class' => string 'Regular' (length=7)
'price' => int 300
In the above scenario y function shuld return false because even though my arrays have the same number of elements the price property of the second index is different, first array has 200 ad second array has 300.
在上面的场景中,y函数shuld返回false,因为即使我的数组具有相同数量的元素,第二个索引的price属性也不同,第一个数组有200个ad第二个数组有300个。
Also if for some reason array 1 has more elements than array 2 then it should also return false.
此外,如果由于某种原因,数组1具有比数组2更多的元素,那么它也应该返回false。
What would be the best way of doing this? Bets in terms of speed and performance.
这样做的最佳方式是什么?在速度和性能方面投注。
I was thinking of converting both arrays to json and checking them like a string.
我正在考虑将两个数组转换为json并像字符串一样检查它们。
2 个解决方案
#1
3
array_diff() is there for this purpose. And its ok if the arrays are small, but for optimization, check out this post. It involves flipping the array value and key for faster comparison. And also this other stack comment for a hash table approach.
array_diff()就是为了这个目的。如果数组很小就可以,但是为了优化,请查看这篇文章。它涉及翻转数组值和键以便更快地进行比较。还有这个哈希表方法的其他堆栈注释。
#2
4
Try this
尝试这个
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
#1
3
array_diff() is there for this purpose. And its ok if the arrays are small, but for optimization, check out this post. It involves flipping the array value and key for faster comparison. And also this other stack comment for a hash table approach.
array_diff()就是为了这个目的。如果数组很小就可以,但是为了优化,请查看这篇文章。它涉及翻转数组值和键以便更快地进行比较。还有这个哈希表方法的其他堆栈注释。
#2
4
Try this
尝试这个
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.