【发布时间】: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