【问题标题】:How to sort a multi dimensional array in PHP alphabetically?如何按字母顺序对 PHP 中的多维数组进行排序?
【发布时间】:2011-10-31 06:52:17
【问题描述】:

我用 PHP (Codeigniter) 编写的 API 根据选定的关键字输出用户如何在输出到 JSON 之前按字母顺序对该数组进行排序。

这是输出:

http://pastie.org/2402372

感谢所有输入!

【问题讨论】:

  • 为什么不在 Model 的查询中直接对其进行排序?
  • 我不能。该数组是不同查询的组合。
  • 我需要按名字排序。

标签: php arrays codeigniter sorting


【解决方案1】:

这个有效。久经考验,真实可靠:

function sort_by_lastname($a, $b) {
    $a = trim($a['user']['basic'][0]['lastname']);
    $b = trim($b['user']['basic'][0]['lastname']);
    return strcmp($a,$b);
}

uasort($array['contacts'],'sort_by_lastname');

【讨论】:

  • 你可以使用 strcmp 代替两次比较
  • @RiaD 谢谢,忘了它在相等时也返回 0。代码已更新。
【解决方案2】:

您可以为此使用 usort:http://php.net/manual/en/function.usort.php

这使您可以使用自己的函数进行排序。

例子:

$users = $your_array['contacts'];
// or $users = $your_array->contacts;

usort ($users, 'sort_by_lastname');

$your_array['contacts'] = $users;
// or $your_array->contacts = $users; if it's json instead of array

function sort_by_lastname($a, $b)
{
    return strcmp($a['user']['basic']['lastname'], $b['user']['basic']['lastname']);
}

【讨论】:

  • 听起来很有趣!我看了一点,我无法构造一个适用于我的数组的函数。能不能给我看看怎么用?
  • 我可以将 sort_by_lastname 函数放在 helper 中,然后在控制器中使用 usort 函数吗?如何使用代码?我收到错误:使用未定义的常量 sort_by_lastname - 假定为“sort_by_lastname”。
  • 恐怕还是有问题。
  • @Jonathan Clark:也许我们最好去聊天看看问题出在哪里
  • 为什么不只是usort ($your_array['contacts'], 'sort_by_lastname'); ??
猜你喜欢
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多