Mat*_*der 6 php arrays compare
有没有一种快速的方法来做这样的事情比较两个具有相同值但在PHP中具有不同顺序的数组?
我的数组可能具有相同的数据,但顺序不同,我只需看看它们是否相同.
好吧,事实证明我得到一个对象而不是一个数组,我猜...
object(Doctrine\ORM\PersistentCollection)#560 (9) etc.
Run Code Online (Sandbox Code Playgroud)
嗯...最容易的方法是迭代集合的内容,以便创建我自己的数组然后像你们所建议的那样进行比较?
只需为我的最终解决方案添加代码
//Find out if container receives mediasync
$toSync = array();
foreach($c->getVideosToSync() as $v) {
$toSync[] = $v->getId();
}
$inSync = array();
foreach($c->getVideosInSync() as $v) {
$inSync[] = $v->getId();
}
$noDiff = array_diff($toSync, $inSync);
$sameLength = count($toSync) === count($inSync);
if( empty($noDiff) && $sameLength ) {
$containerHelper[$c->getId()]['syncing'] = false;
}
else {
$containerHelper[$c->getId()]['syncing'] = true;
}
Run Code Online (Sandbox Code Playgroud)
Jak*_*uld -3
只需使用 & 使它们按统一顺序排列,sort()然后使用 与它们进行比较array_diff()。
# Set the test data.
$array1 = array(1,2,3,4,9,10,11);
$array2 = array(3,4,2,6,7);
# Copy the arrays into new arrays for sorting/testing.
$array1_sort = $array1;
$array2_sort = $array2;
# Sort the arrays.
sort($array1_sort);
sort($array2_sort);
# Diff the sorted arrays.
$array_diff = array_diff($array1_sort, $array2_sort);
# Check if the arrays are the same length or not.
$length_diff = (count($array1) - count($array2));
$DIFFERENT_LENGTH = ($length_diff != 0) ? true : false;
# Check if the arrays are different.
$ARE_THEY_DIFFERENT = ($array_diff > 1) ? true : false;
if ($DIFFERENT_LENGTH) {
echo 'The are different in length: ' . $length_diff;
}
else {
echo 'They have the same length.';
}
echo '<br />';
if ($ARE_THEY_DIFFERENT) {
echo 'They are different: ' . implode(', ', $array_diff);
}
else {
echo 'They are not different.';
}
echo '<br />';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2503 次 |
| 最近记录: |