Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

Sorting Multi Dimensional Array in PHP

//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;
}
Source by www.techantena.com #
 
PREVIOUS NEXT
Tagged: #Sorting #Multi #Dimensional #Array #PHP
ADD COMMENT
Topic
Name
9+5 =