Close

php

How to Sort Multidimensional Arrays Using PHP

In this video, you’ll learn how to sort multidimensional arrays in PHP. You’ll not only learn basic sorting using array_multisort(), but you’ll also see a more advanced custom function for sorting multidimensional arrays by a specific key.

Multidimensional arrays can be one of the more confusing parts about learning PHP, but this video will help you get your head around it and give you some tools for sorting your multidimensional arrays that are simple and straight-forward.

<?php
$arr = array(
array('name' => 'John', 'age' => 30, 'website' => 'http://learnphp.co'),
array('name' => 'Joe', 'age' => 28, 'website' => 'http://johnmorrisonline.com'),
array('name' => 'Amy', 'age' => 32, 'website' => 'http://amy.com'),
array('name' => 'Alex', 'age' => 22, 'website' => 'http://thealex.com'),
array('name' => 'Pat', 'age' => 40, 'website' => 'http://patsjourney.com'),
);

?>

<pre><?php print_r($arr); ?></pre>

<?php
array_multisort($arr);
?>

<pre><?php print_r($arr); ?></pre>

<?php
function val_sort($array,$key) {

//Loop through and get the values of our specified key
foreach($array as $k=>$v) {
$b[] = strtolower($v[$key]);
}

print_r($b);

asort($b);

echo '<br />';
print_r($b);

foreach($b as $k=>$v) {
$c[] = $array[$k];
}

return $c;
}

$sorted = val_sort($arr, 'website');
?>

<pre><?php print_r($sorted); ?></pre>

December 29, 2011