Jump to content

Sort array keys with keys that start with underscores first..


Scooby08

Recommended Posts

Say I have this array:

 

<?php
$array = array('one' => array(), 'two' => array(), '_three' => array());
?>

 

How could I sort that array so it ends up like so:

 

Array
(
    [_three] => Array
        (
        )

    [one] => Array
        (
        )

    [two] => Array
        (
        )
)

 

Thanks!!

There is a function for sorting by keys. Did you even look in the manual? ksort()

 

I can understand if you maybe didn't know how underscores would be sorted, but you could of at least tried. You would have found that it sorts exactly as you want.

Tried that.. If it were only that easy.. It sorts with underscores last..

 

I'm thinking it might have to have some sort of usort function written for it.. The following used to work, but my array has changed and now it needs to be modified to work with keys rather than values..

 

<?php
function sortUnderscoreToFront($a, $b) {
    if (substr($a['category'], 0, 1) == '_' || substr($b['category'], 0, 1) == '_') {
        return ((substr($a['category'],0,1)=='_')?-1:1);
    }
    return strcmp(strval($a['category']), strval($b['category']));
}
usort($templates_array, 'sortUnderscoreToFront');
?>

Tried that.. If it were only that easy.. It sorts with underscores last..

 

No it does not. Underscores come before numbers.

$array = array('one' => array(), 'two' => array(), '_three' => array());
ksort($array);
echo "<pre>".print_r($array, true)."</pre>";

 

Output

Array
(
    [_three] => Array
        (
        )

    [one] => Array
        (
        )

    [two] => Array
        (
        )

)

Ok I figured out why mine wasn't working. Some of the keys begin with a capital letter. I need to sort something more like this and I do not want to change the case of the keys either..

 

<?php
$array = array('One' => array(), 'two' => array(), '_three' => array());
ksort($array);
echo "<pre>".print_r($array, true)."</pre>";
?>

 

Output

Array
(
    [One] => Array
        (
        )

    [_three] => Array
        (
        )

    [two] => Array
        (
        )

)

 

 

//Case insensitive key sort
function iksort($a, $b)
{
    return strcasecmp(strtolower($a), strtolower($b));
}

$array = array('One' => array(), 'two' => array(), '_three' => array());
uksort($array, 'iksort');
echo "<pre>".print_r($array, true)."</pre>";

 

Output

Array
(
    [_three] => Array
        (
        )

    [One] => Array
        (
        )

    [two] => Array
        (
        )
)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.