按姓氏和名字排序PHP按字母顺序排列

时间:2016-01-14 14:37:20

标签: php sorting

我有这个PHP代码,工作正常。它按姓氏对我的数据进行排序。问题是在对姓氏进行排序后,名字不排序。有人有想法吗?我在php5上运行它。

for ($i = 0; $i <= sizeof($post_data['surname']) - 1; $i++) {

  // Create the object to JSON encode
  $arrData = array(
    'surname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['surname'][$i])))),
    'firstname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['firstname'][$i])))),
    'lastname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['lastname'][$i])))),
    'table' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['table'][$i])))),
  );
  $arrDataFull[] = $arrData;
}


usort($arrDataFull, function ($a, $b){
  return strcmp($a["lastname"], $b["lastname"]);
});

2 个答案:

答案 0 :(得分:0)

你似乎错过了strcmp为你做什么或者usort为你做了什么。 Strcmp比较作为参数给出的两个字符串,并以字母顺序返回第一个字符串是否在第二个字符串之前。

Usort允许您传递将在您的集合上运行的匿名函数,直到它被排序。每次迭代都会比较您从集合中获取的两个元素作为参数($ a和$ b)。在此函数中,您必须定义比较这些参数的方式。

因此,当你将第一个人的名字与第二个人的姓氏进行比较时,你真的没有得到你想要的东西。

相反,首先用姓氏比较两个人,如果他们的姓氏相同,则按照他们的名字比较两个人。

所以你的代码看起来像这样:

for ($i = 0; $i <= sizeof($post_data['surname']) - 1; $i++) {

  // Create the object to JSON encode
  $arrData = array(
    'surname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['surname'][$i])))),
    'firstname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['firstname'][$i])))),
    'lastname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['lastname'][$i])))),
    'table' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['table'][$i])))),
  );
  $arrDataFull[] = $arrData;
}


usort($arrDataFull, function ($a, $b){
  if($a["lastname"] == $b["lastname"]) {
      return strcmp($a["firstname"], $b["firstname"]);
  }

  return strcmp($a["lastname"], $b["lastname"]);
});

答案 1 :(得分:0)

$lastnames = array();
$firstnames = array();

for ($i = 0; $i <= sizeof($post_data['surname']) - 1; $i++) {

  // Create the object to JSON encode

  $fname = str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['firstname'][$i]))));
  $lname = str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['lastname'][$i]))));
  $arrData = array(
    'surname' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['surname'][$i])))),
    'firstname' => $fname,
    'lastname' => $lname,
    'table' => str_replace('"', '\"', str_replace('\\', '\\\\', htmlspecialchars_decode(urldecode($post_data['table'][$i])))),
  );

  $lastnames[] = $lname;
  $firstnames[] = $fname;

  $arrDataFull[] = $arrData;
}

array_multisort($lastnames, SORT_ASC, $firstnames, SORT_ASC, $arrDataFull);
相关问题