Skip to content

Instantly share code, notes, and snippets.

@johnmorris
Last active June 13, 2019 07:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmorris/5481972 to your computer and use it in GitHub Desktop.
Save johnmorris/5481972 to your computer and use it in GitHub Desktop.
How to Sort Multidimensional Arrays Using PHP
<?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>
@kirston
Copy link

kirston commented Dec 3, 2014

This is just Great!!! Would it be possible to output only two values from array with the last print_r ($sorted); for Ex: name and age ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment