gpt4 book ai didi

php - 比较值顺序不同的两个数组

转载 作者:可可西里 更新时间:2023-11-01 13:32:27 26 4
gpt4 key购买 nike

有没有快速的方法来做这样的事情Compare two arrays with the same value but with a different order在 PHP 中?

我有可能包含相同数据但顺序不同的数组,我只需要查看它们是否相同。

好吧,结果我得到了一个对象而不是一个数组,我猜...

object(Doctrine\ORM\PersistentCollection)#560 (9) etc.

嗯...最简单的方法也许是迭代集合的内容以创建我自己的数组,然后像大家建议的那样进行比较?

只需为我的最终解决方案添加代码

        //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;
}

最佳答案

我是这样解决的:

<?php

$arrayOld=array(
'1'=>'32',
'2'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'40',
'6'=>'42',
'7'=>'44',
);

$arrayNew=array(
'2'=>'32',
'1'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'46',
'6'=>'42',
'7'=>'44',
);

/**
* Here we check if there is any difference in keys or values in two arrays
* array_intersect_assoc - returns values that are same in both arrays checking values as well as keys
* array_diff returns the difference between the arrayNew values and those same values in both arrays, returned by array_intersect_assoc
*/
$result = array_diff($arrayNew,array_intersect_assoc($arrayOld, $arrayNew));
print_r($result);


//result is:
Array (
[2] => 32,
[1] => 34,
[5] => 46,
)

/** 我们可以看到,值 32 和 34 的索引不同* 而索引 5 的值也从 40 变为 46*/

关于php - 比较值顺序不同的两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com