开发者

PHP How to order an array in ABC Order from a value of 1 of it's bounds

开发者 https://www.devze.com 2023-04-01 02:23 出处:网络
Ok, I have an array like so: $my_array = array( \'hi\' => array(\'description\' => \'how are you?\', \'title\' => \'Hello\', \'link\' => \'http://mylink.com\'),

Ok, I have an array like so:

$my_array = array(
    'hi' => array('description' => 'how are you?', 'title' => 'Hello', 'link' => 'http://mylink.com'),
    'bye' => array('description' => array('Goodbye!', 'see ya'), 'title' => 'See Ya Later', 'link' => 'http://mybyelink.com'),
    'not_now' => array('description' => array('I am away now!', 'gone'), 'title' => 'Away', 'link' => 'http://myawaylink.com'),
    'back' => array('description' => array('I am back now!', 'back', 'present'), 'title' => 'Here', 'link' => 'http://mybacklink.com'),
);

So I开发者_StackOverflow中文版 would like the array to be ordered, within php code, somehow so that it orders it by the TITLE of each array bound: $my_array['hi']['title'], $my_array['bye']['title'], $my_array['not_now']['title'], and $my_array['back']['title'], but it MUST keep the array intact so that all of the values within the hi, bye, not_now, and back are the exact same and all of the arrays (if any are in it, are also the same).

So this array will need to be ordered in ABC order depending on the title, so should return in this order:

$my_array = array(
    'not_now' => array('description' => array('I am away now!', 'gone'), 'title' => 'Away', 'link' => 'http://myawaylink.com'),
    'hi' => array('description' => 'how are you?', 'title' => 'Hello', 'link' => 'http://mylink.com'),
    'back' => array('description' => array('I am back now!', 'back', 'present'), 'title' => 'Here', 'link' => 'http://mybacklink.com'),
    'bye' => array('description' => array('Goodbye!', 'see ya'), 'title' => 'See Ya Later', 'link' => 'http://mybyelink.com'),
);

Titles are in ABC order here: Away, Hello, Here, and See Ya Later.

How can I do this and still keep the array intact with all of the sub-arrays in it also?

Thanks guys :)


You want to use the uasort function with a user-defined sort function using strnatcmp in the function. Here is an example for your code:

function titleSort($a, $b) {
    return strnatcmp($a['title'], $b['title']);
}

uasort($my_array, 'titleSort');

If desired you could add some sanity checking on the input variables to make sure they are arrays by using is_array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号