Last active
June 13, 2019 07:26
-
-
Save johnmorris/5481972 to your computer and use it in GitHub Desktop.
How to Sort Multidimensional Arrays Using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ??