Tuesday, 28 June 2016

how to sort Multi-Dimensional Array By Value In PHP

$users =Array(  [0] =>
        Array (
             [username] => a
              [name] => Andrei Zmievski
        )

        [1] => Array (
            [username] => dotjay
            [name] => Jon Gibbins
        )

        [2] => Array  (
              [username] => shiflett
              [name] => Chris Shiflett
        )
    )


<?php
$names = array();
foreach ($users as $user) {
$names[] = $user['name'];}
array_multisort($names, SORT_ASC, $users);


?>

============================================

$orders =Array
(
    [item-1] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )

    [item-2] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [item-3] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )
)

usort($orders, 'sort_by_order ');
function sort_by_order ($a, $b)
{
    return $a['order'] - $b['order'];
}
print_r($orders)

Array
(
    [0] => Array
        (
            [id] => 3
            [title] => Item 3
            [order] => 1
        )

    [1] => Array
        (
            [id] => 2
            [title] => Item 2
            [order] => 2
        )

    [2] => Array
        (
            [id] => 1
            [title] => Item 1
            [order] => 3
        )
)

No comments:

Post a Comment