0

Here is my array:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => West
                    [1] => 4
                )

            [1] => Array
                (
                    [0] => South west
                    [1] => 20
                )

        )

)

What I want to achieve is be able to compare $array[0][0][1] and $array[0][1][1]. So whichever is lesser comes first and I get the value. So in this case I know that 4 is lesser so I get West first then South west is next. It should be dynamic since we can get more than 2.

3
  • You've got a three levels of arrays here, so it's not entirely clear what you intend to sort. Are you trying to sort the outermost array ($array)? Or the array in the middle ($array[0])? Commented Jan 13, 2016 at 16:09
  • 1
    Can you show us what you have tried till now ? Commented Jan 13, 2016 at 16:11
  • As you said it should be dynamic, Please show your final array, which you want to sort, then after i will start working on it. Commented Jan 13, 2016 at 18:33

2 Answers 2

1

This a simple example you can use :

$arr = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

$sortArray = array();

foreach($arr as $val){
    foreach($val as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "age"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_ASC,$arr);

print_r($arr); 
Sign up to request clarification or add additional context in comments.

2 Comments

I see so on this code, you are sorting the array by the lowest first, and then you can just extract it.
@Knide there are different types of sorts, for more info : php.net/manual/en/function.array-multisort.php
0

Assuming the depth of the array structure remains the same, and you only want the very lowest, you can use a simple foreach.

function findLowestName($array) {
    $lowest = 0; // variable to hold the index of the lowest entry.
    // go through every entry in the first array member
    foreach($array[0] as $key => $value) {
        // if this entry is lower than the 'current' lowest, mark this as the new lowest
        if($value[1] < $array[0][$lowest]) {
            $lowest = $key;
        }
    }
    return $array[0][$lowest][0];
}

Built as a function, so you can include it, and call the function, passing it the array as a parameter.

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.