Is it possible to usort a multidimensional array in PHP to be ordered by alternative values, i.e 1/0/1/0/1/0

你离开我真会死。 提交于 2020-03-03 07:40:58

问题


If you have this PHP array:

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

Is there a way to use usort (or other) method that can order it by multidimensional key's value, but instead of being "incremental" (0,0,0,1,1), they would alternate (0,1,0,1,0).

So using the array above as an example, the desired order output is for the keys to be ordered by alternate "order" key value:

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

);

In short; The keys are now ordered by the value of the key called "order" and alternate in value, so they are: 0, 1, 0, 1, 0.

I simply can't figure this one out!


回答1:


No, it's not possible. Ordering means that you can compare two elements and determine which order they should have. Your query fails at that when you have two 1 elements.

However, that doesn't mean that it can't be done algorithmically, only that sorting or ordering is not the right tool for the job.



来源:https://stackoverflow.com/questions/59861053/is-it-possible-to-usort-a-multidimensional-array-in-php-to-be-ordered-by-alterna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!