Showing posts with label multi-dimension. Show all posts
Showing posts with label multi-dimension. Show all posts

Sorting second dimension array

We can sort the second dimension array like table, for example


$users = array(
	array('name' => 'Mr. B', 'age' => 34), 
	array('name' => 'Mr. A', 'age' => 33),
	array('name' => 'Mr. C', 'age' => 32)
);

If you want to sort the array based on the name or age, here is the solution:



function arraySortByColumn(&$arr, $col, $dir = SORT_ASC){
	$sort_col = array();
	foreach ($arr as $key => $row) {
		$sort_col[$key] = $row[$col];
	}
	array_multisort($sort_col, $dir, $arr);
}

arraySortByColumn($users, 'name', SORT_DESC);
print_r($users);