当这些数组的一个元素不同时,你如何比较两个数组以获得真相

我有两个只区分一个元素的数组,即使一个元素不同,我也想得到真相。不同的元素可以位于不同的索引中,在我的示例中它位于数组的第三个索引中。


  $aRoutesByClass = array (

               1 => 'odbiorca',

               2 => 'umowy-z-odbiorcami',

               3 => '{agreement2lvl:id}',

               4 => 'wydarzenia',

                      )



   $aUserSettingUrl = array (

               1 => 'odbiorca',

               2 => 'umowy-z-odbiorcami',

               3 => '13732',

               4 => 'wydarzenia',

                           )



           if ($aRoutesByClass == $aUserSettingUrl) {

                    //FALSE

                    //I wish it were true if only one element is different

                }

我希望我清楚地描述了我的问题。


慕斯王
浏览 87回答 3
3回答

侃侃无极

您可以使用 array_diff() 比较两个数组,它会给出不同元素数组的结果然后您可以检查 count() 是否为 1 然后您将得到 true 尝试以下代码$aRoutesByClass = array (       1 => 'odbiorca',       2 => 'umowy-z-odbiorcami',       3 => '{agreement2lvl:id}',       4 => 'wydarzenia',    );    $aUserSettingUrl = array (            1 => 'odbiorca',            2 => 'umowy-z-odbiorcami',            3 => '13732',            4 => 'wydarzenia',    );    $result = array_diff($aRoutesByClass,$aUserSettingUrl);     if (count($result) == 1) {        echo "true";exit;    }

小怪兽爱吃肉

在某些情况下,表实际上是相等的。示例:$aRoutesByClass = array ( 1 => 'recovery-changes', ) $aUserSettingUrl = array ( 1 => 'recovery-changes', )

幕布斯6054654

如果我明白你的意思,你想比较两个数组,如果只有一个元素不同,它应该显示为真。<?php$aRoutesByClass = array (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1 => 'odbiorca',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 => 'umowy-z-odbiorcami',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 => '{agreement2lvl:id}',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;4 => 'wydarzenia',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp;$aUserSettingUrl = array (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1 => 'odbiorca',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 => 'umowy-z-odbiorcami',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 => '13732',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;4 => 'wydarzenia',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;);$counter = 0;for($i = 1; $i<= count($aRoutesByClass); $i++){&nbsp; &nbsp; if($aRoutesByClass[$i] != $aUserSettingUrl[$i]){&nbsp; &nbsp; &nbsp; &nbsp; $counter++;&nbsp; &nbsp; }}if($counter == 1){&nbsp; &nbsp; echo "Even";}else{&nbsp; &nbsp; echo "Odd";}?>
打开App,查看更多内容
随时随地看视频慕课网APP