【问题标题】:Array : how to get file position by natural order sorting?数组:如何通过自然顺序排序获取文件位置?
【发布时间】:2019-03-15 15:32:23
【问题描述】:

我想按自然顺序对文件夹中的文件进行排序。 这些文件是:“1-Test1.docx”、“2-Test2.docx”、“3-Test3.docx”、“10-Test10.docx”。

当我使用以下内容时:

for( $i= 0 ; $i <= 4; $i++ ){
    $nomfichier = glob("vendor/templates/part3/*.docx");
    natsort ($nomfichier);
    print_r ($nomfichier);
}

我有:

Array ( [0] => folder1/folder2/1-Test1.docx [2] => folder1/folder2/2-Test2.docx [3] => folder1/folder2/1-Test3.docx [1] => folder1/folder2/10-Test10.docx ) 

没关系。但是当我尝试使用相同的自然顺序回显每个位置时,它会在“1-Test1.docx”之后给我“10-Test10.docx”。

    $position = array_search($nomfichier[$i], $nomfichier);
   // echo $nomfichier[$i]. " : ". $position;

给...

folder1/folder2/1-Test1.docx : 0 folder1/folder2/10-Test10.docx : 1 folder1/folder2/2-Test2.docx : 2 folder1/folder2/3-Test3.docx : 3 

而我希望得到以下结果:

folder1/folder2/1-Test1.docx : 0 folder1/folder2/2-Test2.docx : 1 folder1/folder2/3-Test3.docx : 2 folder1/folder2/10-Test10.docx : 3 

我该怎么做才能让它工作?

谢谢!!

【问题讨论】:

  • 您是使用 for 循环还是 foreach 循环打印?
  • 我使用 for 循环来打印结果。

标签: php arrays sorting for-loop


【解决方案1】:

natsort 对数组进行排序,但键保持不变。因此,当您打印0 索引的值时,它将打印10-Test10.docx。要正确实现这一点,您可以使用array_multisortSORT_NATURAL 标志,如下所示:

for( $i= 0 ; $i <= 4; $i++ ){
    $nomfichier = glob("uploads/*.jpeg");
    array_multisort($nomfichier, SORT_NATURAL);
    $position = array_search($nomfichier[$i], $nomfichier);
    echo $nomfichier[$i]. " : ". $position;
}

希望对你有帮助。

【讨论】:

  • 太好了,正是我想要的,非常感谢!
【解决方案2】:

因为您使用的是 for 循环,所以索引将覆盖排序。
当您 for 循环并 echo $arr[1] 时,无论排序显示什么,它仍然是数组中的第 1 项。

另一方面,Foreach 不循环索引并遵循排序顺序。

// Your array
$arr = array (
  0 => 'folder1/folder2/1-Test1.docx ',
  2 => 'folder1/folder2/2-Test2.docx ',
  3 => 'folder1/folder2/1-Test3.docx ',
  1 => 'folder1/folder2/10-Test10.docx ',
);

foreach($arr as $val){
    echo $val . PHP_EOL;
}

输出:

folder1/folder2/1-Test1.docx 
folder1/folder2/2-Test2.docx 
folder1/folder2/1-Test3.docx 
folder1/folder2/10-Test10.docx 

https://3v4l.org/J3SkA

如果您出于任何原因需要知道索引键值,则可以使用foreach($arr as $key =&gt; $val){,$key 将是数组的索引。

【讨论】:

  • 非常感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2023-03-20
  • 1970-01-01
  • 2014-05-18
  • 2021-11-08
  • 2013-01-07
相关资源
最近更新 更多