0

I have the following array:

Array
(
    [0] => Array
        (
            [0] => 2
            [1] => 1
            [2] => Text
            [3] => 0

        )

    [1] => Array
        (
            [0] => 3
            [1] => 1
            [2] => Another Text
            [3] => 0

        )   
}

I need to order the outter array by the value of the index number 2 of the inner array so it would be:

Array
(
    [0] => Array
        (
            [0] => 2
            [1] => 1
            [2] => Another Text
            [3] => 0

        )

    [1] => Array
        (
            [0] => 3
            [1] => 1
            [2] => Text
            [3] => 0

        )   
}

I found methods like sort() and array_multisort() but it seems that they do not fit in this case. Also the original array has many items so it should be a fast algorithm.

Does php has any implemented method for this case?

Sherif
  • 11,786
  • 3
  • 32
  • 57
Guilherme Longo
  • 605
  • 3
  • 9
  • 18
  • Order them how, exactly? Your example merely swaps `$arr[1][2]` with `$arr[0][2]`, which doesn't exactly conform with your description of expected behavior. – Sherif Aug 26 '16 at 14:10
  • Ah yes, your description of the problem and your code doesn't match. I wrote my answer following the description and not your sample result. – MartinMouritzen Aug 26 '16 at 14:14

2 Answers2

0

You can use the usort function, something like:

function sortBySecondIndex($a,$b) {
    return strnatcmp($a[2],$b[2]);
}

usort($array,"sortBySecondIndex");
MartinMouritzen
  • 221
  • 1
  • 2
  • 12
0

Well, I can't say how fast this would be, but couldn't you do something like:

$tmpArray = array();
foreach($multiDimArray as $index=>$array)
{
    $tmpArray[$array[2]] = $index;
}
ksort($tmpArray);

$finalArray = array();
foreach($tmpArray as $sortedIndex)
{
    $finalArray[] = $multiDimArray[$sortedIndex];
}

Although, I'm sure there has to be a more elegant way to do this.

P. Gearman
  • 1,138
  • 11
  • 14