Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort arrays by specific key inside another array [duplicate]

Possible Duplicate:
Sort multidimensional Array by Value (2)

How can i sort array by specific key inside it:

array(
  array(5, 2),
  array(5, 3),
  array(3, 1),
  array(5, 4)
);

It's an array that has several arrays with 2 values, how do i sort by the second value of each array, so result would be :

array(
  array(5, 1),
  array(5, 2),
  array(3, 3),
  array(5, 4)
);
like image 399
Osa Avatar asked Sep 23 '26 22:09

Osa


2 Answers

Here's one way of doing it:

<?php

$input = array(
    array(5, 2),
    array(5, 3),
    array(3, 1),
    array(5, 4)
);

/**
 * Funkily sort the input array.
 * 
 * @param array $array
 *
 * @return array
 */
function funky_sort(array $array) {
    //Get the array of the first elements
    $first_elements = array_map(function($el) {
        return $el[0];
    }, $array);

    //Get the array of the second elements
    $second_elements = array_map(function($el) {
        return $el[1];
    }, $array);

    //Sort the second elements only
    sort($second_elements, SORT_NUMERIC);

    //Combine both arrays to the same format as the original
    $result = array();
    for ($i = 0; $i < count($first_elements); $i++) {
        $result[] = array($first_elements[$i], $second_elements[$i]);
    }

    //Fire away
    return $result;

}

var_dump(funky_sort($input));
like image 153
Madara's Ghost Avatar answered Sep 26 '26 12:09

Madara's Ghost


Here are some directions which won't solve your problem (the sort is strange) but can lead you to the solution. You can use the usort function ( http://www.php.net/manual/en/function.usort.php ) and define your own comparator.

If you know your sorting logic, add it to the cmp function, which returns 0, if the two elements are equal, -1 if $a < $b and 1 otherwise.

The code will look something like this:

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

$a = array(
  array(5, 2),
  array(5, 3),
  array(3, 1),
  array(5, 4)
);

usort($a, "cmp");
like image 21
Radoslav Georgiev Avatar answered Sep 26 '26 14:09

Radoslav Georgiev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!