views:

40

answers:

2

Let's say I've started here:

$arr[0] = array('a' => 'a', 'int' => 10);
$arr[1] = array('a' => 'foo', 'int' => 5);
$arr[2] = array('a' => 'bar', 'int' => 12);

And I want to get here:

$arr[0] = array('a' => 'foo', 'int' => 5);
$arr[1] = array('a' => 'a', 'int' => 10);
$arr[2] = array('a' => 'bar', 'int' => 12);

How can I sort the elements in an array by those elements' elements?

Multidimensional arrays always feel like a little bit more than my brain can handle (-_-) (until I figure them out and they seem super easy)

+2  A: 

Do you want to order them by the value of the "int" key ?

Use uasort with a callback function :

function compare_by_int_key($a, $b) {
    if ($a['int'] == $b['int']) {
        return 0;
    }
    return ($a['int'] < $b['int']) ? -1 : 1;
}
uasort($arr, "compare_by_int_key");
mexique1
A: 

first off, dont forget to change the index variable you are using to reference the array cuz right now you only have two elements in the base array because you assign a value to $arr[1] twice.

Here is a the code:

// for the number of elements in the base array
for ( $eye = 0; $eye < sizeOf($arr); $eye += 1) {
    // grab each element in the array
    for ( $jay = 0; $jay < sizeOf($arr); $jay += 1) {
        // if the second element of the base array's current element
        // is greater than the next one
        if ( $arr[$jay][1] > $arr[$jay + 1][1] ) {
            // then swap those values
            $temp = $arr[$jay]
            $arr[$jay] = $arr[$jay+1]
            $arr[$jay+1] = $temp
        }
    }
}

Keep in mind I didn't test this code so you may have to do a small amount of debugging. This should sort the way you want it to, there are faster ways to perform this search but this is the simplist and I tried to give you some explanation in the comment code.

Hope this helps, Gale

GEShafer