【问题标题】:Sort array by name with array key [duplicate]使用数组键按名称对数组进行排序[重复]
【发布时间】:2019-03-09 10:11:06
【问题描述】:

我有一个这样的数组,如何按“名称”排序

Array ( 
    [0] => Array ( 
        [id] => 1 
        [name] => status_category_confide 
    ) 
    [1] => Array ( 
        [id] => 2 
        [name] => status_category_love 
    ) 
    [2] => Array ( 
        [id] => 3 
        [name] => status_category_household 
    ) 
    [3] => Array ( 
        [id] => 4 
        [name] => status_category_family 
    ) 
    [4] => Array (
        [id] => 5 
        [name] => status_category_friends 
    ) 
    [5] => Array ( 
        [id] => 6 
        [name] => status_category_colleague 
    ) 
    [6] => Array ( 
        [id] => 7 
        [name] => status_category_work 
    ) 
    [7] => Array ( 
        [id] => 8 
        [name] => status_category_ambition 
    ) 
)

我尝试过使用“排序”功能,但它不起作用

$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
    //array_push($status_category, constant($gsm['name']));
    $status_category[] = array(
        "id"=>$gsm['id'],
        "name"=>$gsm['name']
    );
}

sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
    echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}

我想按名字的顺序显示结果

【问题讨论】:

  • ^ 那是为了在 PHP 中对其进行排序。但正如下面的答案所示,您可以(并且可能应该)直接在查询中对其进行排序。
  • 未来访问者请注意:无需添加更多使用 PHP 对其进行排序的答案。上面可能的重复链接中涵盖了所有内容。不要重复或多或少相同的答案,而是将其投票为重复。

标签: php


【解决方案1】:

按选项尝试 SQL 顺序

$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");

【讨论】:

  • 但我用 constant() 更改了数据库中的结果
【解决方案2】:

您可以使用array_columnarray_multisort 函数对其进行排序。

$keys = array_column($array, 'name');

array_multisort($keys, SORT_ASC, $array);

【讨论】:

  • 非常酷,感谢您的帮助,简单的代码和工作!
【解决方案3】:

您可以尝试使用用户定义的比较函数按值对数组进行排序

   function cmp($a, $b)
{
  return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");

【讨论】:

    【解决方案4】:
    $a = array();
    $a[] = array('id' => 1, 'name' => 'status_category_confide');
    $a[] = array('id' => 2, 'name' => 'status_category_love');
    $a[] = array('id' => 3, 'name' => 'status_category_household');
    
    function cmp($x, $y) {
        if (strcmp($x['name'], $y['name']) == 0) {
            return 0;
        }
        return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
    }
    usort($a, "cmp");
    
    print_r($a);
    

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      相关资源
      最近更新 更多