Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array by a child array's value in PHP

I have an array composed of arrays. I want to sort the parent array by a property of the child arrays. Here's an example

array(2){
    [0]=> array(3){
        [0]=> string(6) "105945"
        [1]=> string(10) "First name"
        [2]=> float(0.080878465391)
    }
    [1]=> array(3) {
        [0]=> string(6) "109145"
        [1]=> string(11) "Second name"
        [2]=> float(0.0504154818384)
    }
}

I would like to sort the parent array by [2] ascending in the child arrays, so in this case the result would be the child arrays reversed (.05, 08). Is this possible using any of the numerous PHP sort functions?

like image 959
Evan Avatar asked Apr 20 '10 06:04

Evan


People also ask

How do you sort an array by a specific value in PHP?

PHP - Sort Functions For Arraysrsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key. arsort() - sort associative arrays in descending order, according to the value.

What is the index value of an array's first element?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .

What is K sort in PHP?

The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.


3 Answers

You can make use of usort function as:

$arr = array(
    array("105945", "First name", 0.080878465391),
    array("109145", "Second name", 0.0504154818384)
);

function cmp($a, $b){
    if($a[2] == $b[2]){
        return 0;
    }
    return ($a[2] < $b[2]) ? -1 : 1;
}

usort($arr, "cmp");
like image 93
codaddict Avatar answered Sep 20 '22 11:09

codaddict


As of PHP >= 7.0 you can use usort in combination with the spaceship operator

usort($arr, function ($a, $b) {
        return $a[2] <=> $b[2];
    });

see: http://php.net/manual/de/migration70.new-features.php

like image 27
HKandulla Avatar answered Sep 18 '22 11:09

HKandulla


For database like patterns use array_multisort as seen in example #3.

For example:

$sort = array();
foreach ($data as $key => $row) {
  $sort[$key]  = $row['basis'];
}
array_multisort($sort, SORT_ASC, $data);

where $data is your data array and basis is the element used for sorting.

like image 35
dude2511 Avatar answered Sep 20 '22 11:09

dude2511