Twifty
Twifty

Reputation: 3378

Preserving order of values in associative array

Lets say I have an array like

$array = array(
    'abc' => true,
    'def' => true,
    'ghi' => true,
    'jkl' => false
);

This is an over simplified example, in actuality the values are objects which have a status of 'active' or 'inactive'.

class myObject {
    var $tab_name;
    var $active;
}

This is used to build an array of tabs for a tab view where order is important.

Now if I toggle one of my values

$array['abc'] = false;
$array['jkl'] = true;

How can I reorder the array (actually an ordered map) so that the true values remain at the front, retaining their order (any additions should be appended) and the false values remain at the rear (order NOT important)?

IE. I expect the output to be:

array (
    'def' => true,
    'ghi' => true,
    'jkl' => true,
    'abc' => false
);

All I know beforehand is the key of the value being toggled.

Upvotes: 0

Views: 109

Answers (2)

GeminiDomino
GeminiDomino

Reputation: 451

It doesn't appear that any of the builtin array sorting functions let you access both key and value at the same time, which seems to be what you need here, since the sorting algorithms behind the scenes don't look to be stable.

I scratched this up (coded for clarity rather than elegance), it might help. It doesn't do "in place" sorting, but if the dataset isn't too huge, it might do what you need to.

function group_array($ary){
    $t = array();
    $f = array();
    $res = array();
    foreach (array_keys($ary) as $k){ //Assuming that you're 100% sure that the input array keys are already ordered
        if ($ary[$k] == 'true') {
            $t[] = $k;
        } else if ($ary[$k] == 'false') {
            $f[] = $k;
        }
    }
    foreach ($t as $true_key){
        $res[$true_key] = 'true';
    }
    foreach ($f as $false_key){
        $res[$false_key] = 'false';
    }

    return $res;
}

Upvotes: 2

Digital Chris
Digital Chris

Reputation: 6202

If the array uses "Active" and "Inactive" as you specified, you can just use asort($array), which will return all "Active" values at the top since it's an alpha sort.

Upvotes: 0

Related Questions