0

I have an array that is not ordered sequentially by ID however the [post_title] which is essentially the file name and it does retain the sequential number based values.

How can I get the first element ID in an array then the second and so on but sequentially based off the number of the element [post_name] or [post_title]?

For Example: get first array element id

$pmockupzero = current($media)->ID; 

get second array element id

$pmockuponea = array_slice($media, 1, 1, true);
$pmockupone = current($pmockuponea)->ID; 

But these do not take into account the sequential [post_name].

Array
(
[104682] => WP_Post Object
    (
        [ID] => 104682
        [post_title] => 45232-183.jpg
        [post_name] => 45232-183-jpg
    )
[104681] => WP_Post Object
    (
        [ID] => 104681
        [post_title] => 45232-182.jpg
        [post_name] => 45232-182-jpg
    )
[104679] => WP_Post Object
    (
        [ID] => 104679
        [post_title] => 45232-180.jpg  
        [post_name] => 45232-180-jpg
    )
[104680] => WP_Post Object
    (
        [ID] => 104680
        [post_title] => 45232-181.jpg
        [post_name] => 45232-181-jpg
    )

)

user2059376
  • 431
  • 5
  • 15

1 Answers1

1

You can use uasort() to provide your own sorting function for the array.

PHP Manual - Arrays - uasort

uasort($media, function ($a, $b) {
    return strnatcmp($a->post_title, $b->post_title);
});

$first_item_by_title = current($media);

note: I use natural string comparison so that title2 would sort ahead of title10

PHP Manual - Strings - Natural Comparison

Rob_vH
  • 760
  • 8
  • 11