最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何按 PHP 中内部数组的字段之一对多维数组进行排序?

SEO心得admin52浏览0评论
本文介绍了如何按 PHP 中内部数组的字段之一对多维数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个模拟数据库表的数组.每个数组元素代表一行,每行内是另一个包含字段名称和值的数组.

Suppose I have an array that mimics a database table. Each array element represents a row, and within each row is another array that contains the field names and values.

Array ( [0] => Array ( [name] => 'Sony TV' [price] => 600.00 ) [1] => Array ( [name] => 'LG TV' [price] => 350.00 ) [2] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) }

我想做的是按价格对行(外部数组元素)进行排序.以下是我想要实现的示例:

What I want to do is sort the rows (outer array elements) by price. Below is an example of what I want to achieve:

Array ( [0] => Array ( [name] => 'LG TV' [price] => 350.00 ) [1] => Array ( [name] => 'Samsung TV' [price] => 425.00 ) [2] => Array ( [name] => 'Sony TV' [price] => 600.00 ) }

如您所见,我不需要保留外部数组的键.

As you can see, I don't need to preserve the keys of the outer array.

推荐答案

您需要使用 usort,一个通过用户定义的函数对数组进行排序的函数.类似的东西:

You need to use usort, a function that sorts arrays via a user defined function. Something like:

function cmp($a, $b) { if ($a["price"] == $b["price"]) { return 0; } return ($a["price"] < $b["price"]) ? -1 : 1; } usort($yourArray,"cmp")
发布评论

评论列表(0)

  1. 暂无评论