Last active
December 19, 2015 19:48
-
-
Save nachodd/6008576 to your computer and use it in GitHub Desktop.
multidimensional array sort by giver key. ordenar array multidimensional por una clave dada.
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 | |
$people = array( | |
array("name"=>"Bob","age"=>8,"colour"=>"red"), | |
array("name"=>"Greg","age"=>12,"colour"=>"blue"), | |
array("name"=>"Andy","age"=>5,"colour"=>"purple") | |
); | |
var_dump($people); | |
$sortArray = array(); | |
foreach($people as $person){ | |
foreach($person as $key=>$value){ | |
if(!isset($sortArray[$key])){ | |
$sortArray[$key] = array(); | |
} | |
$sortArray[$key][] = $value; | |
} | |
} | |
$orderby = "name"; //change this to whatever key you want from the array | |
array_multisort($sortArray[$orderby],SORT_DESC,$people); | |
var_dump($people); | |
/*Function - Función*/ | |
function array_sortByGivebKey($array, $orderby, $desc=false) { | |
$sortArray = array(); | |
$orden = $desc==true ? SORT_DESC : SORT_ASC; | |
foreach($array as $arr){ | |
foreach($arr as $key=>$value){ | |
if(!isset($sortArray[$key])){ | |
$sortArray[$key] = array(); | |
} | |
$sortArray[$key][] = $value; | |
} | |
} | |
array_multisort($sortArray[$orderby],$orden,$array); | |
return $array; | |
} | |
/*Another way - Otra forma*/ | |
function sortByField($multArray,$sortField,$desc=false){ | |
$tmpKey=''; | |
$ResArray=array(); | |
$maIndex=array_keys($multArray); | |
$maSize=count($multArray)-1; | |
for($i=0; $i < $maSize ; $i++) { | |
$minElement=$i; | |
$tempMin=$multArray[$maIndex[$i]][$sortField]; | |
$tmpKey=$maIndex[$i]; | |
for($j=$i+1; $j <= $maSize; $j++) | |
if($multArray[$maIndex[$j]][$sortField] < $tempMin ) { | |
$minElement=$j; | |
$tmpKey=$maIndex[$j]; | |
$tempMin=$multArray[$maIndex[$j]][$sortField]; | |
} | |
$maIndex[$minElement]=$maIndex[$i]; | |
$maIndex[$i]=$tmpKey; | |
} | |
if($desc) | |
for($j=0;$j<=$maSize;$j++) | |
$ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]]; | |
else | |
for($j=$maSize;$j>=0;$j--) | |
$ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]]; | |
return $ResArray; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment