ds0409 2013-12-18 09:22
浏览 80
已采纳

保持关联数组中的值顺序

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.

  • 写回答

2条回答 默认 最新

  • drcx71276 2013-12-18 09:59
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部