Home > front end >  PHP natsort() not sorting my URLs as I think it should
PHP natsort() not sorting my URLs as I think it should

Time:01-13

I am trying to sort image URLs and send back the image which is alphabetically first to show as featured image. Here is the code I have so far:

$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];

First I retrieve the array of images which is a json file, then I put each thumbnail URL in a thumbnail_array which is then sorted and returned. This doesn't seem to work however, I tried to log $thumbnail_array[0] and $thumbnail_array[1] before and after the sorting and here is what I got as an example:

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

Nothing happens after the sort, shouldn't 1 come before 2? Why is this? Am I missing something obvious (probably yes)?

CodePudding user response:

natsort retains key-value association:

$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"
}

So yes, 0 will still be the 0 value and so on, but their order changed within the array. You can reset the keys if you want to renumber the values:

natsort($thumbnail_array);
$thumbnail_array = array_values($thumbnail_array);
  •  Tags:  
  • php
  • Related