简体   繁体   English

如何对数组中的浮点数进行排序?

[英]How to sort floats in an array?

I tried sort , Ksort , multiSort , nothing is working and I'm not sure why.I can use print_r and see that it is an array but it won't sort just keeps giving errors. 我尝试了sortKsortmultiSort ,什么都没有用,我不确定为什么。我可以使用print_r看到它是一个数组,但不会排序只会给出错误。 I think it is because the values are floats but I may be wrong. 我认为这是因为值是floats但我可能是错的。

Here's a page with the array shown using print_r function: 这是使用print_r函数显示数组的页面:

http://forcedchange.testdomain.pw/gallery/ http://forcedchange.testdomain.pw/gallery/

Here is my code: 这是我的代码:

<?php 
$uploads = wp_upload_dir(); //Path to my gallery uploads folder
if ($dir = opendir($uploads['basedir'].'/gallery-2')) {
    $images = array();
    while (false !== ($file = readdir($dir))) { 
        if ($file != "." && $file != "..") {
            $images[] = $file; 
        }
    }
     closedir($dir);
}

$images = ksort($images);  /* not working */
// echo '<pre>';
// echo print_r($images);
// echo '</pre>';
foreach($images as $image) {
    echo '<figure><img src="';
    echo $uploads['baseurl'].'/gallery-2/'. $image;
    echo '" alt="" /></li>';
    echo '<figcaption>';
    echo '<p>' .  erq_shortcode() . '</p>';
    echo '</figcaption>';
    echo '</figure>';

}
?>

Try using natsort($images) (don't know which result you want). 尝试使用natsort($images) (不知道您想要哪个结果)。 It should sort the array like: 它应该像这样对数组排序:

1.png
2.png
...
9.png
10.png
...
20.png

Assigning won't work because the sort-funcs return a bool... the sorting is done direct inside the given array. 分配将不起作用,因为sort-funcs返回一个布尔值...排序直接在给定数组内完成。

$images=glob("/path/*.{jpg,png,gif}");

ksort($images);

foreach($images as $image)
{
...
... do something with basename($image);
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM