PHP – Array Multi Sorting

Finally, simple but powerful function to sort Multi Array by specified Index

function sortArray(&$arr, $indexToSort, $sortBy = 'asc'){
	$arr2bSorted = array();
	foreach ($arr as $k => $v){
		$arr2bSorted[ $v['id']] = $v[$indexToSort];
		foreach ($v as $k2 => $v2){
			if (is_array($v2)){
				if (!empty($arr[$k][$k2])){
					sortArray($arr[$k][$k2], $indexToSort);
				}
			}
		}
	}
	$sortedArr = array();
	if ($sortBy == 'asc'){
		asort($arr2bSorted);
	}
	else{
		arsort($arr2bSorted);
	}
	foreach ($arr2bSorted as $id => $v){
		$sortedArr[$id] = $arr[$id];
	}
	$arr = null;
	$arr = $sortedArr;
}

Your comments are pretty much appreciated.

Tags:

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.