mysql如何对数组进行排序按值保持在 PHP 中的钥匙?

标签: MySQL PHP
发布时间: 2015/6/12 0:29:55
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我弄不懂为什么搭配并不工作。任何其他排序也不工作。$hs ['hs_type'] 是来自 MySQL 查询的值。

$results = $query->result_array();
$hs_types = array();
foreach($results as $hs) {
    $hs_types[$hs['hs_type']]++;
}

$projects = array();
foreach($hs_types as $hs) {
    array_push($projects, $hs);
}
asort($projects);

var_dump 为我之前排序的数组: 数组 (大小 = 15)

  * 8 => int 1709
  * 13 => int 26
  * 7 => int 474
  * 14 => int 800
  * 11 => int 282
  * 6 => int 61
  * 5 => int 23
  * 15 => int 181
  * 3 => int 2
  * 19 => int 3
  * 9 => int 50
  * 1 => int 44
  * 2 => int 2
  * 4 => int 4
  * 18 => int 13

var_dump 为我后排序的数组: 数组 (大小 = 15)

  * 8 => int 2
  * 12 => int 2
  * 9 => int 3
  * 13 => int 4
  * 14 => int 13
  * 6 => int 23
  * 1 => int 26
  * 11 => int 44
  * 10 => int 50
  * 5 => int 61
  * 7 => int 181
  * 4 => int 282
  * 2 => int 474
  * 3 => int 800
  * 0 => int 1709

我想要:

  * 3 => int 2
  * 2 => int 2
  * 19 => int 3
  * 4 => int 4
  * 18 => int 13
  * 5 => int 23
  * 13 => int 26
  * 1 => int 44
  * 9 => int 50
  * 15 => int 181
  * 11 => int 282
  * 7 => int 474
  * 14 => int 800
  * 8 => int 1709

解决方法 1:

问题是你是一切进入您很好地低回的数组,然后将每个项目推到 $projects 数组 (失去关键) 然后做搭配 $projects 阵列上的。

它总是带着这个小测试脚本:-

<?php

$hs_types = array(8 =>  1709,
   13 =>  26,
   7 =>  474,
   14 =>  800,
   11 =>  282,
   6 =>  61,
   5 =>  23,
   15 =>  181,
   3 =>  2,
   19 =>  3,
   9 =>  50,
   1 =>  44,
   2 =>  2,
   4 =>  4,
   18 =>  13);

Echo "\r\nOriginal array\r\n";
print_r($hs_types);

$projects = array();
foreach($hs_types as $hs) 
{
    array_push($projects, $hs);
}

asort($projects);

Echo "\r\nPushed array sorted\r\n";
print_r($projects);

asort($hs_types);

Echo "\r\nOriginal array sorted\r\n";
print_r($hs_types);

?>

但它看起来像它会容易只是放在第一位在 SQL 中得到排序后的列表。

赞助商