Quantcast
Channel: PHP Freaks: PHP Help
Viewing all articles
Browse latest Browse all 13200

Function to sort multidimensional array by a value

$
0
0

Sorry for being in the wrong forum but I couldn't post in the Code Snippets section.

 

Here is a quick function that will sort a multidimensional array by a given value

function subval_sort(array $array, $subkey, $reverse = false)
{
	if (empty($array))
	{
		return array();
	}

	$temp_array = array();

	foreach ($array as $key => $value)
	{
		$temp_array[$key] = strtolower($value[$subkey]);
	}
		
	if ($reverse)
	{
		arsort($temp_array);
	}
	else
	{
		asort($temp_array);	
	}

	$_array = array();

	foreach ($temp_array as $key => $value)
	{
		$_array[] = $array[$key];
	}
	
	return $_array;
}

It can be used as such:

$array = [
    0 => [
        'value' => 6
    ],
    1 => [
        'value' => 2
    ],
    2 => [
        'value' => 1
    ]
]
$array = subval_sort($array, 'value');

This would return:

[
    0 => [
        'value' => 1
    ],
    1 => [
        'value' => 2
    ],
    2 => [
        'value' => 6
    ]
]

And it can be reversed by specifying a third parameter (bool)

$array = subval_sort($array, 'value', true);

Viewing all articles
Browse latest Browse all 13200

Trending Articles