【问题标题】:PHP natsort() not sorting my URLs as I think it shouldPHP natsort() 没有按照我认为应该的方式对我的 URL 进行排序
【发布时间】:2023-01-12 20:28:27
【问题描述】:

我正在尝试对图像 URL 进行排序,并发回按字母顺序排在第一位的图像以显示为特色图像。这是我到目前为止的代码:

$image_array = get_post_meta($postID, "image_array", true);
$thumbnail_array = array();
    for ($i = 0; $i < count($image_array ); $i++) {
        $thumbnail_array[] = $image_array [$i]['thumbnail'];
    }
    natsort($thumbnail_array);
    return $thumbnail_array[0];

首先,我检索图像数组,这是一个 json 文件,然后我将每个缩略图 URL 放在一个 thumbnail_array 中,然后对其进行排序并返回。但是,这似乎不起作用,我尝试在排序前后记录 $thumbnail_array[0] 和 $thumbnail_array[1],这就是我得到的示例:

Before natsort:
[0]: https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg
[1]: https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg

After natsort: 
[0]: https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg
[1]: https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg

排序后没有任何反应,1 不应该在 2 之前吗?为什么是这样?我是否遗漏了一些明显的东西(可能是)?

【问题讨论】:

  • 它排序正确,如下所示:onlinephp.io/c/53140 问题可能出在代码的其他地方。
  • natsort 不会解除键与其值的关联。数组元素已排序,但保留了它们的键,因此当您引用 [0] 时,您仍在引用该数据值,尽管它现在位于数组中的不同偏移位置。

标签: php


【解决方案1】:

natsort 保留键值关联:

$a = [
    'https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg',
    'https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg'
];

natsort($a);
var_dump($a);
array(2) {
  [1]=>
  string(74) "https://example.com/staging/wp-content/uploads/2022/08/image1-263x350.jpeg"
  [0]=>
  string(74) "https://example.com/staging/wp-content/uploads/2022/08/image2-263x350.jpeg"
}

所以是的,0 仍将是 0 值等等,但它们在数组中的顺序发生了变化。如果要对值重新编号,可以重置键:

natsort($thumbnail_array);
$thumbnail_array = array_values($thumbnail_array);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2010-10-27
    • 2011-12-09
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多