Sort an array using a specific key

I have the following array:

Array
(
    [Places] => Array
        (
            [public] => 0
            [entities] => Array
                (
                    ...
                )
        )
    [Issues] => Array
        (
            [public] => 1
            [entities] => Array
                (
                    ...
                )
        )

    [Source] => Array
        (
            [public] => 0
            [entities] => Array
                (
                    ...
                )
        )
)

I would like to be able to sort by array with public key. I know that I may have to use ksortor usort, but I'm not sure how to implement this.

Any ideas would be greatly appreciated!

+3
source share
6 answers
usort($array, function ($a, $b) { return $a["public"] - $b["public"]; });
+4
source

Here's an interesting link: http://www.the-art-of-web.com/php/sortarray/

I would try

usort(usort(array, function), function);

I can try the sample code on request, but the information already exists for adoption.

+1
source

, array_multisort:

$test   =   array(
        'Places' => array(
            'public' => 0,
            'entities' => array(

            )
        ),
        'Issues' => array(
            'public' => 1,
            'entities' => array()
        ),
        'Source' => array(
            'public' => 0,
            'entities' => array()
        )
    );

    echo '<pre>';
    print_r($test);
    echo '</pre>';

    array_multisort($test,SORT_ASC,$test);

    echo '<pre>';
    print_r($test);
    echo '</pre>';
0

array_multisort , , , .

:

$test   =   array(
    'Places' => array(
        'public' => 0,
        'entities' => array(

        )
    ),
    'Issues' => array(
        'public' => 1,
        'entities' => array()
    ),
    'Source' => array(
        'public' => 0,
        'entities' => array()
    )
);

echo '<pre>';
print_r($test);
echo '</pre>';

$sort = array();
foreach ($test as $k => $a) {
    $sort[$k] = $a['public'];
}

// placing $sort first in array_multisort causes $test to be sorted in same order as the values in $sort
array_multisort($sort,SORT_ASC,$test);

echo '<pre>';
print_r($test);
echo '</pre>';
0

You can use usort with callback function.

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

usort($array, "cmp");
0
source

Try the following:

$code = "return (-1*strnatcmp(\$a['public'], \$b['public']));";
uasort($array, create_function('$a,$b', $code));
0
source

Source: https://habr.com/ru/post/1753701/


All Articles