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条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP