简体   繁体   English

对PHP中的子键值排序多级数组

[英]Sort multilevel array on sub key value in PHP

I want to sort below multilevel array on ascending order of price value.我想按price值的升序对多级数组进行排序。

{
    "pData": [
    {
        "name": "Walmart",
        "address": "Full Address for Walmart",
        "pricing": [{
            "id": "Samsung Galaxy 21M",
            "price": 157.0,
        }],
    },
    {
        "name": "Stop & Shop",
        "address": "Full Address for Stop & Shop",
        "pricing": [{
            "id": "Samsung Galaxy 21M",
            "price": 142.0,
        }],
    },
    {
        "name": "Safeway",
        "address": "Full Address for Safeway",
        "pricing": [{
            "id": "Samsung Galaxy 21M",
            "price": 148.0,
        }],
    }
    ],
    "status ":" ok "
}

I tried below code but giving same result without sorting array on value of price key.我尝试了下面的代码,但给出了相同的结果,而没有对price键的值进行排序。 I even tried many similar codes from different answers on this site but none of working.我什至在这个网站上尝试了许多来自不同答案的类似代码,但都没有工作。 So please advise what is wrong with my code or suggest completely different code.所以请告知我的代码有什么问题或建议完全不同的代码。

function cmp($a, $b)
{
    //if ($a["price"] == $b["price"]) // Try #1
    if($a["pData"]["pricing"]["price"] == $b["pData"]["pricing"]["price"]) // Try #2
    {
        return 0;
    }
    return ($a["price"] < $b["price"]) ? -1 : 1; // Try #1
    return ($a["pData"]["pricing"]["price"] < $b["pData"]["pricing"]["price"]) ? -1 : 1;
}

usort($result,"cmp");
print_r($result);

You should be pretty close with what you have.你应该非常接近你所拥有的。 You don't need the pData index in your callback, instead pass $result['pData'] to usort.您不需要回调中的 pData 索引,而是将 $result['pData'] 传递给 usort。

function cmp($a, $b)
{
    if ($a["pricing"][0]["price"] == $b["pricing"][0]["price"])
    {
        return 0;
    }

    return ($a["pricing"][0]["price"] < $b["pricing"][0]["price"]) ? -1 : 1;
}

usort($result["pData"],"cmp");
print_r($result);

I just noticed that you have an array of objects at the pricing element, so sorting the pData element in its current form will be problematic.我刚刚注意到您在定价元素中有一个对象数组,因此以当前形式对 pData 元素进行排序将有问题。 You may want to pull all of the pricing elements out into a seperate data structure first and then sort that new structure.您可能希望首先将所有定价元素提取到一个单独的数据结构中,然后对该新结构进行排序。 Something like this may help you get to a better working solution:像这样的事情可能会帮助您获得更好的工作解决方案:

$tmp = array();
foreach ($result["pData"] as $pData) {
    foreach ($pData["pricing"] as $pricing) {
        $tmp[] = array(
            "name" => $pData["name"],
            "address" => $pData["address"],
            "id" => $pricing["id"],
            "price" => $pricing["price"]
        );
    }
}

function cmp($a, $b)
{
    if ($a["price"] == $b["price"])
    {
        return 0;
    }

    return ($a["price"] < $b["price"]) ? -1 : 1;
}

usort($tmp,"cmp");
print_r($tmp);

You can use spaceship operator <=> also known as three-way comparison operator.您可以使用飞船运算符<=>也称为三向比较运算符。

usort($result["pData"], function ($a, $b) {
    return $a["pricing"][0]["price"] <=> $b["pricing"][0]["price"];});

For PHP 7.4 with arrow function.对于带有箭头功能的 PHP 7.4。

usort($result["pData"], fn($a, $b) => $a["pricing"][0]["price"] <=> $b["pricing"][0]["price"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM