Memory App
Programming
 




Sort


$arr = array('da', 'b', 'c');

sort($arr); // [ b, c, da ]
natsort() - Sort an array using a "natural order" algorithm

$arr = array('10t', '2t', '3t');

natsort($arr); // [1] => 2t [2] => 3t [0] => 10t
natcasesort - case insensitive

$arr = array('10t', '2T', '2t', '3t');

natsort($arr); // [ 2T, 2t, 3t, 10t ]

natcasesort($arr); // [ 2t, 2T, 3t, 10t ]
(1/4)

Usort

usort() - Sort an array by values using a user-defined comparison function This short script allows us to sort an array by a rather complicated set of rules.

$arr = array('three', '2two', 'one', 'two');

function myCmp($left, $right) {
    
    // sort according to the length of each element.

    if ($diff = strlen($left) - strlen($right)) {
        return $diff;
    }

    // Elements whose values have the same length 
    // are further sorted using regular string comparison.

    return strcmp($left, $right);
}

usort($arr, 'myCmp'); //  [0] => one [1] => two [2] => 2two [3] => three
(2/4)

Filter

array_filter() - Filters elements of an array using a callback function If no callback is supplied, all entries of the $input's empty values are remove

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

// return true if integer is odd (bitwise &)

function odd($var) { return ($var & 1); }

// return true if integer is odd

function even($var) { return (!($var & 1)); }

print_r(array_filter($arr, 'odd')); //  [0] => 1 [2] => 3 [4] => 5

print_r(array_filter($arr, 'even'));// [1] => 2 [3] => 4 [5] => 6
Mmore compact

$result = array_filter(array(1,2,3), 

    create_function('$x', 'return $x & 1;')
); 

// [ 1, 3 ]
Without callback, will return only non emtpy values

$input = array(0=>'a', 1=> false, 2=> null, 3=> 'b');

$output = array_filter($input); // [ a, b ] 
(3/4)

Multisort

array_multisort() - Sort multiple or multi-dimensional arrays Example 1

$arr1 = array(3,2,1);
$arr2 = array(4,8,0);

array_multisort($arr1, $arr2);

print_r($arr1); // [ 1, 2, 3 ]
print_r($arr2); // [ 0, 8, 4 ]

// The entries in the second array
// corespond to the identical entries in arr1
Example 2

$arr = array(
    array("10", 11, 100, 100, "a"),
    array(1, 2, "2", 3, 1),
);

array_multisort(
    $arr[0], SORT_ASC, SORT_STRING,
    $arr[1], SORT_DESC, SORT_NUMERIC);

print_r($arr);

// [ "10", 11, 100, 100, "a" ]
// [ 1, 3, "2", 2, 1 ]
// 1 coresponds to "a"
Example 3

$data = array(
    array('a' => 1, 'b' => 2),
    array('a' => 2, 'b' => 3),
    array('a' => 2, 'b' => 1),
    array('a' => 1, 'b' => 1),
);

foreach ($data as $k => $v) {
    $a[$k] = $v['a'];
    $b[$k] = $v['b'];
}

array_multisort($a, SORT_DESC, $b, SORT_ASC, $data);

/* ordered array will be:
$data = array(
    array('a' => 2,    'b' => 1),
    array('a' => 2,    'b' => 3),
    array('a' => 1,    'b' => 1),
    array('a' => 1,    'b' => 2),
);
*/


Questions



Top Reference > Programming
0/0 (80)  
Not Logged