PHP 按字段名称对多维数组进行排序

发布于 2024-09-17 18:20:13 字数 272 浏览 2 评论 0原文

我尝试调整此代码以用于对命名键/字段上的多维数组进行排序。该字段是一个整数,我需要将其从最小到最大排序。

function myCmp($a, $b)
{
    return strcmp($a["days"], $b["days"]);
}

uasort($myArray, "myCmp");

这会根据我的需要对数组进行排序,但顺序错误。目前它从最大到最小排序,不使用自然顺序。我需要按自然顺序从最小到最大排序(例如,2 在 5、12 和 24 之前)。

I have tried adapting this code to use to sort a multidimensional array on a named key/field. The field is an integer what I need to sort smallest to biggest.

function myCmp($a, $b)
{
    return strcmp($a["days"], $b["days"]);
}

uasort($myArray, "myCmp");

This sorts the arrays as I need but in the wrong order. At the moment it sorts biggest to smallest, not using natural order. I need to sort smallest to biggest in natural order (eg 2 comes before 5, 12 and 24).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

碍人泪离人颜 2024-09-24 18:20:13

strnatcmp() 是你的朋友

,例如(使用 php 5.3 闭包/匿名函数):

<?php
$myArray = array( 'foo'=>array('days'=>2), 'bar'=>array('days'=>22), 'ham'=>array('days'=>5), 'egg'=>array('days'=>12) );
uasort($myArray, function($a, $b) { return strnatcmp($a["days"], $b["days"]); });

foreach($myArray as $k=>$v) {
  echo $k, '=>', $v['days'], "\n";
}

打印

foo=>2
ham=>5
egg=>12
bar=>22

strnatcmp() is your friend

e.g. (using a php 5.3 closure/anonymous function):

<?php
$myArray = array( 'foo'=>array('days'=>2), 'bar'=>array('days'=>22), 'ham'=>array('days'=>5), 'egg'=>array('days'=>12) );
uasort($myArray, function($a, $b) { return strnatcmp($a["days"], $b["days"]); });

foreach($myArray as $k=>$v) {
  echo $k, '=>', $v['days'], "\n";
}

prints

foo=>2
ham=>5
egg=>12
bar=>22
长亭外,古道边 2024-09-24 18:20:13

您可以反转 strcmp 的参数:

function myCmp($a, $b)
{
  return strcmp($b["days"], $a["days"]);
}

uasort($myArray, "myCmp");

You can just reverse the parameters of strcmp :

function myCmp($a, $b)
{
  return strcmp($b["days"], $a["days"]);
}

uasort($myArray, "myCmp");
岁吢 2024-09-24 18:20:13

由于您想按自然顺序排序,因此您不应该使用 strcmp,您可以这样做:

function myCmp($a, $b)
{
  if ($a['days'] == $b['days']) return 0;
  return ($b['days'] > $a['days']) ? -1 : 1;
}

这是一个 工作示例

Since you want to sort in natural order you should not be using strcmp, you can do:

function myCmp($a, $b)
{
  if ($a['days'] == $b['days']) return 0;
  return ($b['days'] > $a['days']) ? -1 : 1;
}

Here is a working example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文