如何订购“斑马"数组,因此每个键都有一个备用值(1、0) [英] How to order "zebra" array so each key has an alternate value (either 1, 0)

查看:76
本文介绍了如何订购“斑马"数组,因此每个键都有一个备用值(1、0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有以下PHP数组:

If you have this PHP array:

$args = array(
    'a' => array(
        'zebra' => 1,
    ),
    'b' => array(
        'zebra' => 0,
    ),
    'c' => array(
        'zebra' => 0,
    ),
    'd' => array(
        'zebra' => 0,
    ),
    'e' => array(
        'zebra' => 1,
    ),
);

是否有一种方法可以通过斑马"键值以算法方式更改此数组的顺序,但是它们不是增量"(0,0,0,1,1),而是交替(0,1, 0,1,0).

Is there a way to algorithmically change the order of this array by the "zebra" key value, but instead of being "incremental" (0,0,0,1,1), they would alternate (0,1,0,1,0).

因此,使用上面的示例,所需的完成数组将如下所示:

So using the example above, the desired finished array will look like this:

$ordered_args = array(
    'b' => array(
        'zebra' => 0,
    ),
    'a' => array(
        'zebra' => 1,
    ),
    'c' => array(
        'zebra' => 0,
    ),
    'e' => array(
        'zebra' => 1,
    ),
    'd' => array(
        'zebra' => 0,
    ),

);

任何额外的重复项都应附加到末尾,因此解决方案应允许其他数组,例如具有(1,1,1,1,0,0)的斑马值的数组,其结果将为(0,1 ,0,1,1,1)

Any extra duplicates should be appended to the end, so the solution should allow for other arrays such as ones with zebra values like (1,1,1,1,0,0), which would result in (0,1,0,1,1,1)

我根本想不通!

我试图通过

I tried to do this with usort, via this similar, but different, question, and the answer was no, so I am looking for a programatic solution (without usort).

推荐答案

将输入分为1和0的想法相同,只要有剩余要输出的内容,就输出0和1.每次输出一个值时,数组都会减少,这会一直持续到两个列表都为空,因此应该处理不平衡的列表...

Same idea to split the input into the 1's and 0's, then output a 0 and a 1 as long as there is something left to output. As each time you output a value, the array is reduced, this just continues till both lists are empty so should cope with unbalanced lists...

$temp = [ 0 => [], 1 => []];

foreach($args as $key=>$value){
    $temp[$value['zebra']][] = $key;
}

$output = [];
while ( !empty($temp[0]) || !empty($temp[1]) )   {
    if ( !empty($temp[0]) )   {
        $next = array_shift($temp[0]);
        $output [$next] = $args[$next];
    }
    if ( !empty($temp[1]) )   {
        $next = array_shift($temp[1]);
        $output [$next] = $args[$next];
    }
}

这篇关于如何订购“斑马"数组,因此每个键都有一个备用值(1、0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆