Sorting on the content of the content of a specific item in a multi-dimensional array

I have a multi-dimensional array that looks like this:

Array
(
[1] => Array
(
[vid] => 1
[media] => Giclee
[size] => 12"x12"
[price] => 100.00
)

[2] => Array
    (
        [vid] => 2
        [media] => Silk on Wood
        [size] => 12"x12"
        [price] => 75.00
    )

[3] => Array
    (
        [vid] => 3
        [media] => Giclee
        [size] => 24"x24"
        [price] => 4000.00
    )

)

I want to sort it so that the top level array items (the ones with numeric keys) are ordered alphabetically on the content of the nested item with the key “media.”

I have looked at the function array_multisort but can’t figure out how to set it up to do what I want.

Can anyone help me?

Thanks,

–Kenoli

It’s possible, but quickly, how are you getting this data?

Ah, you’re offline.

Okay, ideally if this was data from a database you’d ask for the results to be already sorted with ORDER BY foo DESC|ASC.

You can however, use [fphp]usort/fphp. Here’s a crude example…


<?php
$products = array(
    array('id' => 1, 'name' => 'c'),
    array('id' => 2, 'name' => 'd'),
    array('id' => 3, 'name' => 'a'),
    array('id' => 4, 'name' => 'e'),
    array('id' => 5, 'name' => 'b'),
);


function sortBy($prop, $a, $b){
    return $a[$prop] > $b[$prop];
}


function sortByName($a, $b){
    return sortBy('name', $a, $b);
}


usort($products, 'sortByName');


var_dump($products);


/*
    array(5) {
      [0]=>
      array(2) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(1) "a"
      }
      [1]=>
      array(2) {
        ["id"]=>
        int(5)
        ["name"]=>
        string(1) "b"
      }
      [2]=>
      array(2) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(1) "c"
      }
      [3]=>
      array(2) {
        ["id"]=>
        int(2)
        ["name"]=>
        string(1) "d"
      }
      [4]=>
      array(2) {
        ["id"]=>
        int(4)
        ["name"]=>
        string(1) "e"
      }
    }
*/

Off Topic:

Please don’t do this! The function being used for the sorting should return zero if the items are considered equal, positive if a is to be considered greater than b and negative if a is to be considered less than b. Anthony’s function returns a boolean (as a number, that’s either 0 or 1) which only gets the return value right in two of the three possible comparison outcomes.

Thanks (again? :slight_smile: ) for the body check Salathe.

Hope you’re well.

Anthony.