0

I have a user defined multidimensional array that I am trying to sort. I looked around, and say only how to sort single dimensional arrays, or associative arrays with keys... So, if I have the following...

$treasure = array( array("Banana", "Yellow"), 
    array("Apple", "red"), 
    array("Pear", "green"), 
    array("Peach", "orange"), 
    array("Orange", "orange"), 
    array("Kiwi", "green"));

How do I sort the array so the first element of the interior array is alphabetical? So I would end up with...

$treasure = array( array("Apple", "red"),
    array("Banana", "Yellow"), 
    array("Kiwi", "green")
    array("Orange", "orange"),
    array("Peach", "orange"),  
    array("Pear", "green"), 
    );
3
  • 3
    array_multisort($treasure); print_r($treasure); ? This was asked many times! Commented Jan 18, 2015 at 22:35
  • array_multisort didnt work. I checked many pages before posting this question. Commented Jan 18, 2015 at 23:34
  • Worked fine for me see: ideone.com/7cqjeI Commented Jan 18, 2015 at 23:35

2 Answers 2

1

You could use usort:

<?php
function cmp($a, $b)
{
    return strcmp(reset($a), reset($b));
}

usort($treasure , "cmp");
Sign up to request clarification or add additional context in comments.

Comments

0

Use usort() and provide own comparator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.