在PHP中使用嵌套键对数组进行排序
本文最后更新于 334 天前,其中的信息可能已经有所发展或是发生改变。

在开发过程中,我们经常需要对数组进行排序。PHP提供了很多内置的排序函数,例如sort、asort、ksort等。但是,如果我们需要基于数组的某个嵌套键进行排序,那么就需要一些额外的技巧。

在本文中,我们将介绍如何在PHP中根据嵌套键对数组进行排序。这可以在任何层次的嵌套数组中使用,并且可以根据需要动态地进行排序。我们将首先创建一个可以处理嵌套键路径的函数,然后再使用这个函数进行排序。

首先,我们需要一个可以处理嵌套键路径的函数。键路径是一个用点分隔的字符串,表示如何在数组中找到值。例如,键路径 ‘discount.price’ 表示我们应该查看 ‘discount’ 键下的 ‘price’ 键。下面是一个简单的函数,它可以处理这种键路径:

/**
 * 获取嵌套数组的值
 *
 * @param array $array 要查询的数组
 * @param string $keyPath 键路径,使用'.'分隔
 * @return mixed 返回找到的值,如果没有找到则返回null
 */
function getNestedValue($array, $keyPath)
{
    $keys = explode('.', $keyPath);
    foreach ($keys as $key) {
        if (!isset($array[$key])) {
            return null;
        }
        $array = $array[$key];
    }
    return $array;
}

接下来,我们将使用这个 getNestedValue 函数创建两个排序函数。第一个函数是从低到高排序,第二个函数是从高到低排序:

/**
 * 按照嵌套键的值对数组进行从低到高排序
 *
 * @param array $array 包含数据的数组
 * @param string $keyPath 键路径,使用'.'分隔
 * @return array 返回排序后的数组
 */
function sortByNestedKeyLowToHigh($array, $keyPath)
{
    usort($array['data'], function($a, $b) use ($keyPath) {
        return floatval(getNestedValue($a, $keyPath)) <=> floatval(getNestedValue($b, $keyPath));
    });
    return $array;
}

/**
 * 按照嵌套键的值对数组进行从高到低排序
 *
 * @param array $array 包含数据的数组
 * @param string $keyPath 键路径,使用'.'分隔
 * @return array 返回排序后的数组
 */
function sortByNestedKeyHighToLow($array, $keyPath)
{
    usort($array['data'], function($a, $b) use ($keyPath) {
        return floatval(getNestedValue($b, $keyPath)) <=> floatval(getNestedValue($a, $keyPath));
    });
    return $array;
}

现在,我们可以使用这些函数对任何层次的嵌套数组进行排序。这可以让我们的代码更加灵活和可重用,因为我们可以根据需要动态地选择排序字段。

怎么使用?

示例数据:

{
	"current_page": 1,
	"data": [{
		"pro_id": 3305,
		"pro_num": "911",
		"index_color": "black",
		"size_text": "Large",
		"name": "Lachlan",
		"picture": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/c_thumb,c_scale\/product\/911\/black_m.webp",
		"discount": {
			"key": 0,
			"price": "3.95",
			"o_price": false,
			"discount_ratio": 0,
			"special_link_price_key": 0,
			"vip_price_key": 0
		},
		"color_relation_array": [{
			"cid": 126396,
			"cname": "black",
			"color_img": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/img\/color\/black.png",
			"pro_img": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/c_thumb,w_500,c_scale\/product\/911\/black_3.webp",
			"is_wish": 0
		}],
		"is_wish": 0
	}, {
		"pro_id": 3222,
		"pro_num": "58007",
		"index_color": "black",
		"size_text": "Large",
		"name": "Kirsi",
		"picture": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/c_thumb,c_scale\/product\/58007\/black_m.webp",
		"discount": {
			"key": 0,
			"price": "10.95",
			"o_price": false,
			"discount_ratio": 0,
			"special_link_price_key": 0,
			"vip_price_key": 0
		},
		"color_relation_array": [{
			"cid": 132339,
			"cname": "black",
			"color_img": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/img\/color\/black.png",
			"pro_img": "https:\/\/wherelight-cdn-res.cloudinary.com\/image\/upload\/c_thumb,w_500,c_scale\/product\/58007\/black_3.webp",
			"is_wish": 0
		}],
		"is_wish": 0
	}],
	"next_page_url": null,
	"path": "https:\/\/mdg.api.berf1.cn\/api\/products\/v1\/list\/getList",
	"per_page": 18,
	"prev_page_url": null,
	"to": 11,
	"total": 11
}

使用示例:当我需要将价格从低到高进行排序

$listData=上面的json数据...
//价格低到高
if ($sort === 3) {
 $sortListData = sortByNestedKeyLowToHigh($listData['data'], 'discount.price');
 $listData['data'] = $sortListData;
}
//价格高到低
if ($sort === 4) {
 $sortListData = sortByNestedKeyHighToLow($listData['data'], 'discount.price');
 $listData['data'] = $sortListData;
}

总的来说,通过在PHP中使用嵌套键,我们可以更灵活地对数组进行排序。希望这篇文章能帮助你在你的项目中处理类似的问题。如果你有任何问题或想法,欢迎在下面留言分享。

知识共享许可协议
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇