Sort Multi Dimensional Array in PHP

June 9, 2022
PHP

You may already know how to sort an array in PHP using various array sorting functions like sort, asort, ksort, arsort, krsort.

Here we discuss how to sort a multi dimensional array in PHP.

Sorting Multi Dimensional Array in PHP by Key-Value

I have created a function like following to sort multi dimensional array in PHP using a specific key-value.


//Products Array
$products = [
	[
		'id' => 1,
		'title' => 'Laptop',
		'stock' => 12,
	],[
		'id' => 2,
		'title' => 'Mobile',
		'stock' => 30,
	],[
		'id' => 3,
		'title' => 'USB Cable',
		'stock' => 5,
	],[
		'id' => 4,
		'title' => 'Power Bank',
		'stock' => 53,
	],[
		'id' => 5,
		'title' => 'Mobile Charger',
		'stock' => 28,
	],
];

//Sort array by stock in descending order
$sorted_products = sort_array_by_key($products, 'stock');
print_r($sorted_products);


//Function to sort array by key
function sort_array_by_key($array, $sort_key){
	$key_array = array_column($array, $sort_key);
	array_multisort($key_array, SORT_DESC, $array); //or SORT_ASC
	return $array;
}

Output


/**
OUTPUT
*/
Array
(
    [0] => Array
        (
            [id] => 4
            [title] => Power Bank
            [stock] => 53
        )

    [1] => Array
        (
            [id] => 2
            [title] => Mobile
            [stock] => 30
        )

    [2] => Array
        (
            [id] => 5
            [title] => Mobile Charger
            [stock] => 28
        )

    [3] => Array
        (
            [id] => 1
            [title] => Laptop
            [stock] => 12
        )

    [4] => Array
        (
            [id] => 3
            [title] => USB Cable
            [stock] => 5
        )

)

About Author
Adeeb C (233 Articles)

Adeeb C is a Web Designer, Web Application Developer, Android App Developer, WordPress Developer, Professional Blogger. He has 5 years of experience in WordPress, Web Developing, Professional Blogging, and 2 years of experience in Android App Developing.