如何根据布尔值对数组进行排序

时间:2021-07-10 07:23:28

I have an array that looks something like this:

我有一个这样的数组:

array(
  array('foo' => true),
  array('foo' => false),
  array('foo' => true),
  array('foo' => true),
  array('foo' => false)
)

Is there a simple way to bring all the arrays where foo == true to the top?

是否有一种简单的方法可以将所有的数组(foo == true)带到顶部?

2 个解决方案

#1


5  

Just use the uasort() function to order your array:

只需使用uasort()函数来命令您的数组:

$arr = array(
    array('foo' => true),
    array('foo' => false),
    array('foo' => true),
    array('foo' => true),
    array('foo' => false)
);

function sortit($a, $b) {
    if($a['foo'] === $b['foo']) {
        return 0;
    }

    return $a['foo'] > $b['foo'] ? -1 : 1;
}

uasort($arr, 'sortit');

#2


0  

rsort() will actually do that for you:

rsort()实际上会为您做:

<?php

$a = array(
  array('foo' => true),
  array('foo' => false),
  array('foo' => true),
  array('foo' => true),
  array('foo' => false)
);

rsort($a);

var_dump($a);

Yields:

收益率:

array (size=5)
  0 => 
    array (size=1)
      'foo' => boolean true
  1 => 
    array (size=1)
      'foo' => boolean true
  2 => 
    array (size=1)
      'foo' => boolean true
  3 => 
    array (size=1)
      'foo' => boolean false
  4 => 
    array (size=1)
      'foo' => boolean false

Example: https://eval.in/131577

例如:https://eval.in/131577

Hope this helps!

希望这可以帮助!

#1


5  

Just use the uasort() function to order your array:

只需使用uasort()函数来命令您的数组:

$arr = array(
    array('foo' => true),
    array('foo' => false),
    array('foo' => true),
    array('foo' => true),
    array('foo' => false)
);

function sortit($a, $b) {
    if($a['foo'] === $b['foo']) {
        return 0;
    }

    return $a['foo'] > $b['foo'] ? -1 : 1;
}

uasort($arr, 'sortit');

#2


0  

rsort() will actually do that for you:

rsort()实际上会为您做:

<?php

$a = array(
  array('foo' => true),
  array('foo' => false),
  array('foo' => true),
  array('foo' => true),
  array('foo' => false)
);

rsort($a);

var_dump($a);

Yields:

收益率:

array (size=5)
  0 => 
    array (size=1)
      'foo' => boolean true
  1 => 
    array (size=1)
      'foo' => boolean true
  2 => 
    array (size=1)
      'foo' => boolean true
  3 => 
    array (size=1)
      'foo' => boolean false
  4 => 
    array (size=1)
      'foo' => boolean false

Example: https://eval.in/131577

例如:https://eval.in/131577

Hope this helps!

希望这可以帮助!