按ID排序多维数组PHP

时间:2016-05-31 10:42:29

标签: php arrays sorting

我试图按照我希望它出现的顺序对数组进行多维数组排序。

$lookingfor数组包含我希望它出现的顺序,而$avaliableArray包含整个多维数组。希望结果在示例代码$resultarray

我如何根据id中的$avaliableArray元素执行此操作?

代码:

$avaliableArray = array(       
         array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),

                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);


$lookingFor = array(1,8,4);

寻找结果:

$resultArray = array(       
         array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8"),

                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4")
);

3 个答案:

答案 0 :(得分:1)

使用usort()并将适当的ID应用于$lookingFor,与数组值相同。

$avaliableArray = array(       
         array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),

                array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);


$lookingFor = array("testid-1","testid-8","testid-4");
usort($avaliableArray, function ($a, $b) use ($lookingFor) {
    $pos_a = array_search($a['id'], $lookingFor);
    $pos_b = array_search($b['id'], $lookingFor);
    return $pos_a - $pos_b;
});
echo "<pre>";
print_r($avaliableArray);

<强>输出

Array
(
    [0] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-1
        )

    [1] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-8
        )

    [2] => Array
        (
            [name] => Banken
            [site] => bank
            [avaliable] => 1
            [type] => site
            [id] => testid-4
        )

)

答案 1 :(得分:0)

你应该尝试使用:

function sortIt($a, $b) {
    return strcasecmp($a['id'],$b['id']);
}

usort($resultArray, 'sortIt');

答案 2 :(得分:0)

试试这个:

    <div class="col-xs-12 nopadding verticleCenter">
            <div style="display:flex;">
                <h2 class="slide-title-dark">
                    Prise de Rendez-vous
                </h2>
            </div>
        </div>


.verticleCenter{height:50px;line-height:50px;}