douzhui8531 2014-11-09 00:47
浏览 27
已采纳

如何让PHP natcasesort永久重新排列数组位置?

Looking at the documentation for natcasesort in PHP it sorts the array in a case insensitive way. However after I try to rearrange a two unordered arrays that contain the same letters, and check if they are equivalent it give me false. See below:

$ary=array("b", "z", "A", "C", "S");
$ary1=array("A", "z", "b", "S", "C");
natcasesort($ary);
natcasesort($ary1);
print_r($ary);
print_r($ary1);

if ($ary==$ary1) {
  echo "True";  
} else {
  echo "False";
}

The results I get are:

Array ( [2] => A [0] => b [3] => C [4] => S [1] => z ) 

Array ( [0] => A [2] => b [4] => C [3] => S [1] => z ) 

False

This obviously is because it still saves the original position of the letter in the original array. How can I change the original postion displayed in the brackets to change permanently into an increasing count (in this case 0 to 4 in case-insensitive alphabetical order)?

  • 写回答

1条回答 默认 最新

  • dongqiu7365 2014-11-09 00:53
    关注

    Use array_values to get a new array with new indexes:

    natcasesort($ary);
    natcasesort($ary1);
    
    $ary  = array_values($ary);
    $ary1 = array_values($ary1);
    
    if ($ary == $ary1) {
      echo "True";  
    } else {
      echo "False";
    }
    

    Or if you do this a lot build a function:

    function natcasesortv(&$array) {
        natcasesort($array);    
        $array = array_values($array);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?