如果条件为真,则向上移动PHP数组

时间:2017-10-18 12:41:56

标签: php

我有一个这样的数组:

[
  [id: 1, urgent: true, marketplace: false],
  [id: 2, urgent: true, marketplace: true],
  [id: 3, urgent: false, marketplace: false]
]

数组按顺序排列(默认),顶部有urgent。我需要的是向上移动所有marketplace = true的行。

我尝试了这个,但是没有用:

usort($f, function($a, $b) {
  if ($a['marketplace'] || $b['marketplace']) {
    return 1;
  }
  return 0;
});

3 个答案:

答案 0 :(得分:0)

试试这个:

usort($f, function($a, $b) {
  if ($a['marketplace'] == $b['marketplace']) {
    return 0;
  }
  return $a['marketplace'] ? 1 : -1;
});

答案 1 :(得分:0)

<?php
$data=[
    ['id'=> 1, 'urgent'=> true, 'marketplace'=> false],
    ['id'=> 2, 'urgent'=> true, 'marketplace'=> true],
    ['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
    ['id'=> 3, 'urgent'=> false, 'marketplace'=> true],
    ['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
    ['id'=> 3, 'urgent'=> false, 'marketplace'=> true],
    ['id'=> 3, 'urgent'=> false, 'marketplace'=> false],
];

echo"<pre>";
//print_r($data);


$trueArray=array();
$falseArray=array();
$i=0;
foreach($data as $row){
    if($row['marketplace']==true){
        $trueArray[$i]=$row;
    }
    else{
        $falseArray[$i]=$row;
    }
    $i++;
}

//print_r($trueArray);
//print_r($falseArray);

$result=array_merge($trueArray,$falseArray);
print_r($result);

为更有效的测试添加了更多值。输出是这样的:

    Array
(
    [0] => Array
        (
            [id] => 2
            [urgent] => 1
            [marketplace] => 1
        )

    [1] => Array
        (
            [id] => 3
            [urgent] => 
            [marketplace] => 1
        )

    [2] => Array
        (
            [id] => 3
            [urgent] => 
            [marketplace] => 1
        )

    [3] => Array
        (
            [id] => 1
            [urgent] => 1
            [marketplace] => 
        )

    [4] => Array
        (
            [id] => 3
            [urgent] => 
            [marketplace] => 
        )

    [5] => Array
        (
            [id] => 3
            [urgent] => 
            [marketplace] => 
        )

    [6] => Array
        (
            [id] => 3
            [urgent] => 
            [marketplace] => 
        )

)

marketplace为true的字段位于新数组之上。

答案 2 :(得分:-1)

尝试结合您的条件:

entry.Open()