数组按值和相应的键排序

时间:2013-07-30 06:21:07

标签: php arrays codeigniter sorting

我有一个这样的数组:

        Array
        (
           [1] => 0
           [2] => 1
           [4] => 1
           [5] => 4
           [6] => 2
           [7] => 0
           [8] => 2
           [9] => 7
           [10] => 2
           [11] => 2
           [12] => 2
           [17] => 12
           [18] => 17
           [19] => 0
           [20] => 19
           [21] => 20
           [22] => 20
           [23] => 20
           [24] => 0
         )

我想排序数组,就像第一个所有0值键索引查找并使用此键值索引查找数组中的0值键索引是1,7,19,24和现在1,7,19,24值在数组中查找并且相应的键是get,最后所有键序列都在新数组中获取。可能吗?

3 个答案:

答案 0 :(得分:3)

asort($cars);

example:
asort($cars);
echo "<pre>";
print_r($cars);
echo "</pre>";

答案 1 :(得分:0)

asort($arr);
$arr = array_keys($arr);
print_r($arr);

输出:

Array
(
    [0] => 7
    [1] => 1
    [2] => 19
    [3] => 24
    [4] => 2
    [5] => 4
    [6] => 10
    [7] => 12
    [8] => 11
    [9] => 8
    [10] => 6
    [11] => 5
    [12] => 9
    [13] => 17
    [14] => 18
    [15] => 20
    [16] => 21
    [17] => 23
    [18] => 22
)

答案 2 :(得分:0)

$newTab = array();

foreach ($tab as $k => $v)
{
    $newTab[$v][] = $k;
}

产地:

array (size=9)
  0 => 
    array (size=4)
      0 => int 1
      1 => int 7
      2 => int 19
      3 => int 24
  1 => 
    array (size=2)
      0 => int 2
      1 => int 4
  4 => 
    array (size=1)
      0 => int 5
  2 => 
    array (size=5)
      0 => int 6
      1 => int 8
      2 => int 10
      3 => int 11
      4 => int 12
   ....