Skip to content

Instantly share code, notes, and snippets.

@johnmorris johnmorris/gist:5481972
Last active Jun 13, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.