需要帮助按深度嵌套值排序PHP数组

时间:2013-02-04 17:50:51

标签: php multidimensional-array

提前感谢大家的帮助。

我有以下多维数组:

[list] => Array (
    [0] => Array (
        [retailer] => ABC Store
        [locations] => Array (
            [0] => Array (
                [distance] => 2.86
            )
            [1] => Array (
                [distance] = 5.50
            )
        )
    )

    [1] => Array (
        [retailer] => XYZ Store
        [locations] => Array (
            [0] => Array (
                [distance] => 1.25
            )
            [1] => Array (
                [distance] = 7.50
            )
        )
    )
)

我想根据位置数组中最近的距离对零售商进行排序。因此,新的Array会在XYZ Store之前列出ABC Store

我尝试过使用array_multisort,但是我遇到的问题是将主数组排序到一个嵌套了几层的密钥。

1 个答案:

答案 0 :(得分:0)

$list = array(
    array(
        "retailer" => "ABC Store",
        "locations" => array(
            array(
                "distance" => 2.86
            ) ,
            array(
                "distance" => 5.50
            )
        )
    ) ,
    array(
        "retailer" => "XYZ Store",
        "locations" => array(
            array(
                "distance" => 1.25
            ) ,
            array(
                "distance" => 7.50
            )
        )
    )
);

foreach($list as $info) {
    $storeinfo[$info["retailer"]] = $info;
    foreach($info["locations"] as $location) {
        $distances[] = $location["distance"];
    }
    $stores[$info["retailer"]] = min($distances);
}

natsort($stores);

foreach($stores as $store => $distance) {
    $newlist[] = $storeinfo[$store];
}

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