i have this array

array(
    'pc' => array('count'=>3),
    'xbox' => array('count'=>3),
    'wii' => array('count'=>3),
    '3ds' => array('count'=>3),
    'other' => array('count'=>3),
)

and i want to order it like

array(
    'wii' => array('count'=>3),
    'xbox' => array('count'=>3),
    'other' => array('count'=>3),
    '3ds' => array('count'=>3),
    'pc' => array('count'=>3),
)

im thinking that i need to have another array to sort it by??

the keys might not be the same, so i think an isset() is in order at one point

edit: the criteria is the second array keys

any ideas?

有帮助吗?

解决方案

You will have to define a custom sorting algorithm. You can do that by using PHP's uksort() function. (The difference to the very similar usort() function being that it compares the array's keys instead of its values.)

It could look somewhat like this (requires PHP >= 5.3 because of the anonymous functions I use in it):

<?php
$input = array(
    'pc' => array('count'=>3),
    'xbox' => array('count'=>3),
    'wii' => array('count'=>3),
    '3ds' => array('count'=>3),
    'other' => array('count'=>3),
);
$keyOrder = array('wii', 'xbox', 'other', '3ds', 'pc');

uksort($input, function($a, $b) use ($keyOrder) {
    // Because of the "use" construct, $keyOrder will be available within
    // this function.
    // $a and $b will be two keys that have to be compared against each other.

    // First, get the positions of both keys in the $keyOrder array.
    $positionA = array_search($a, $keyOrder);
    $positionB = array_search($b, $keyOrder);

    // array_search() returns false if the key has not been found. As a
    // fallback value, we will use count($keyOrder) -- so missing keys will
    // always rank last. Set them to 0 if you want those to be first.
    if ($positionA === false) {
        $positionA = count($keyOrder);
    }
    if ($positionB === false) {
        $positionB = count($keyOrder);
    }

    // To quote the PHP docs:
    // "The comparison function must return an integer less than, equal to, or
    //  greater than zero if the first argument is considered to be
    //  respectively less than, equal to, or greater than the second."
    return $positionA - $positionB;
});

print_r($input);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top