#6: Sorting Multidimensional Arrays

One perennial programming task is to sort complicated arrays. For example, let's say that you have this array:

$items = array(
    array("name" => "Mojo Nixon", "price" => 19.96, "quantity" => 2),
    array("name" => "ABBA", "price" => 14.99, "quantity" => 1),
    array("name" => "Iced Earth", "price" => 12.96, "quantity" => 4), 
);

Your goal is to sort this by the name key in each subarray. PHP, like many other scripting languages, has a sort function named usort() that sorts by a user-defined comparison function. In other words, you can sort an array by any criteria you like, and you don't need to fuss with the mechanics of sorting algorithms. The name-based sorting script with usort() boils down to this:

function name_cmp($a, ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.