duanhuantong8278 2013-11-28 19:52
浏览 23
已采纳

比较值不是相同顺序的两个数组

Is there a fast way of doing something like this Compare two arrays with the same value but with a different order in PHP?

I have arrays with potentially same data but in different order and I just need to see whether they are identical.

OK, turns out I get back an object and not an array, I guess...

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

hmm... Would the easiest way perhaps to iterate over the contents of the collection in order to create my own array and then compare like you all suggested?

Just adding code for my final solution

        //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;    
        }
  • 写回答

2条回答 默认 最新

  • duangua5308 2013-11-28 20:02
    关注

    Just get them in a uniform order using sort() & then diff with them with 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 />';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)