Monday, 27 August 2018

PHP - Sorting the multidimensional array according to the key

I am trying to sort an array based on a particular key value in a multidimensional array as follows
<?php
$country = array(
    array(
        'country' => 'India',
        'visits' => 22,
        'newVisits' => 16,
        'newVisitsPercent' => 72.7),
    array(
        'country' => 'USA',
        'visits' => 30,
        'newVisits' => 15,
        'newVisitsPercent' => 50),
    array(
        'country' => 'Japan',
        'visits' => 25,
        'newVisits' => 15,
        'newVisitsPercent' => 60));
?>

I wanna Sort the array in Descending order of the 'visits' key of the array.
Desired Array is
<?php
$country = array(
    array(
        'country' => 'USA',
        'visits' => 30,
        'newVisits' => 15,
        'newVisitsPercent' => 50),
    array(
        'country' => 'Japan',
        'visits' => 25,
        'newVisits' => 15,
        'newVisitsPercent' => 60),
    array(
        'country' => 'India',
        'visits' => 22,
        'newVisits' => 16,
        'newVisitsPercent' => 72.7));
?>

Tried to search in SO all results were sorting based on the value of the key. Please let me know which function do we need to use.
I looked in to ksort, Multi-sort functions

take a look at the documentation of usorthttp://www.php.net/manual/en/function.usort.php

0 comments:

Post a Comment