ds0409 2013-12-18 17: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 17: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条)

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案