如何使用未知索引按子数组值对数组进行排序

时间:2019-03-11 10:12:29

标签: php arrays sorting

我有这个PHP数组:

<?php 

$cities = [
    'amsterdam' => $amsterdam,
    'prague'    => $prague,
    'lisboa'    => $lisboa
];

$amsterdam = [
    65 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'boo',
            'price'   => 100
        ]
    ],
    173 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'hoo',
            'price'   => 2500
        ]
    ],
    ...
];

$prague    = [
    132 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'boo',
            'price'   => 2100
        ]
    ],
    956 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'hoo',
            'price'   => 2500
        ]
    ],
    ...
];

$lisboa    = [
    175 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'boo',
            'price'   => 6500
        ]
    ],
    64 => [
        'table'     => Object
        'something' => false,
        'data'      => [
            'foo'    => 'hoo',
            'price'   => 20
        ]
    ],
    ...
];

?>

我需要按子数组值['data'] ['price']对其进行排序,因此输出如下所示:

<?php
    $cheapest_cities [
        'lisboa'    => $lisboa,    // because 64->data->price is 20
        'amsterdam' => $amsterdam, // beacuse 65->data->price is 100
        'prague'    => $prague     // bacause 132->data->price is 2100
    ];
?>

我尝试了几种usort组合,但是问题是,在我的示例中,我不知道子数组索引是什么(65、173、132、956、175、64)。

您是否知道如何排序?

数据来自数据库:

<?php

        $amsterdam  = $this->getTable()->where(['package_id' => [1,2,3]])->order('package_id')->fetchPairs('id');
        $lisboa     = $this->getTable()->where(['package_id' => [4,5]])->order('package_id')->fetchPairs('id');
        $prague     = $this->getTable()->where(['package_id' => [6]])->order('package_id')->fetchPairs('id');

        return [
            'amsterdam'     => $amsterdam,
            'lisboa'        => $lisboa,
            'prague'        => $prague,
        ];

?>

谢谢

1 个答案:

答案 0 :(得分:0)

请勿使用usort,因为它会删除您的密钥。使用uasort

一个简单的想法: 在uasort的回调函数中,您可以搜索商品的最小值,例如通过array_reduce

array_reduce($city, function($carry, $item) {
    return $carry === 0 ? $item['data']['price'] : min($carry, $item['data']['price']);
}, 0);

此代码段获取城市数组的最小值。然后比较值应该很容易。

Full example

function getMinimumPrice($cityArray) {
    return array_reduce($cityArray, function($carry, $item) {
        return $carry === 0 ? $item['data']['price'] : min($carry, $item['data']['price']);
    }, 0);
}

uasort($cities, function($city1, $city2) {
    $priceCity1 = getMinimumPrice($city1);
    $priceCity2 = getMinimumPrice($city2);

    return $priceCity1 <=> $priceCity2;
});