-1

I have this array:

Array => (
    [0] => Array(
        [a] => hello,
        [b] => world
    ),
    [1] => Array(
        [a] => bye,
        [b] => planet
    ),
    .....
)

And I need a function to sort it into this:

Array => (
    [0] => Array(
        [a] => bye,
        [b] => planet
    ),
    [1] => Array(
        [a] => hello,
        [b] => world
    ),
    .....
)

Been hours trying and I am going mad, please help me.

Thanks!!

1
  • 1
    What is the basis for the sort behavior you want? Why should the elements shown swap places when sorted? That is not clear in your question. Is it alphabetical order by whatever value is at index a? Commented Oct 23, 2014 at 15:44

2 Answers 2

1

If you mean to sort the array based on the contents of all the strings in the array, you're going to have to apply some logic to the sort. Using usort allows us to pass in an arbitrary function to perform the comparison.

usort($my_array, function ($a, $b) {
    return strcasecmp(implode($a), implode($b));
});

This way, it'll compare two arrays like so:

array 1 = [ 'foo', 'bar' ]
array 2 = [ 'baz', 'quux' ]
array 1 is converted to "foobar"
array 2 converted to "bazquux"
compare strings "foobar" to "bazquux"
-> "bazquux" comes first alphabetically, so strcasecmp() return positive integer
-> usort receives the positive integer which informs its sorting algorithm
Sign up to request clarification or add additional context in comments.

1 Comment

And before anyone says so, yes I know this doesn't care about child array ordering, and I know this will break if the array is multi-tiered.
0

You could use array_reverse(). PHP has many built in array functions. http://php.net/manual/en/ref.array.php

$test = Array (
    0 => Array(
        'a' => 'hello',
        'b' => 'world'
),
    1 => Array(
        'a' => 'bye',
        'b' => 'planet'
    ),
);
$reverse = array_reverse($test);
print_r($reverse);
Array ( 
    [0] => Array ( 
        [a] => bye 
        [b] => planet 
    ) 
    [1] => Array ( 
       [a] => hello 
       [b] => world 
    )
 )

1 Comment

The OP said sort, not reverse. What about the implied arbitrary elements in the OP ...?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.