开发者

How to sort an array in this way in php

like the function usort in php but if two members compare as equal, their key should be same. for example: $arrayToSort = array(2,6,1,3,3);

after sort return

array
  1 =>  1
  2 =>  2
  3 =>  3开发者_运维百科
  3 =>  3
  4 =>  6


In response to meder's answer, you're using slow functions such as in_array() and array_push() instead of fast constructs such as isset() or the [] operator. Your code should look like this:

$arr = array(1,2,2,2,3);

$new = array();
foreach ($arr as $v)
{
    $new[$v][] = $v;
}

// then you can sort the array if you wish
ksort($new);

Note that what you're doing is similar, in some way, to PHP's own array_count_values()


You can't have two elements with the same key in an array. You can, however, group the two threes into one array, so that 1=> 1, 2 => 2, and 3 => array(3,3).


You can't have two keys that are the same. Keys are unique.

If you try to create it in code, here's what happens.

$data[1] = 1;  // Assigns value 1 to key 1;   1 element in array
$data[2] = 2;  // Assigns value 2 to key 2;   2 elements in array
$data[3] = 3;  // Assigns value 3 to key 3;   3 elements in array
$data[3] = 3;  // Reassigns value 3 to key 3; STILL 3 elements in array
$data[4] = 6;  // Assigns value 6 to key 4;   4 elements in array


Your example doesn't make sense. You can't have two equal keys in the same array. If you want to sort the array's values and have their keys preserved, use asort(). Or any of the functions in the table at http://ca.php.net/manual/en/array.sorting.php that say "yes" under "Maintains key association".


Not sure if there's a native function but this might be what you want.

<?php
$arr = array(1,2,2,2,3);

function arrayKeyJoin( $arr ) {
    $newArr = array();
    foreach ( $arr as $item ) {
 if ( !in_array( $item, array_keys($newArr) ) ) {
     $newArr[$item] = array();
 }
 array_push( $newArr[$item], $item );
    }
    return $newArr;
}

echo '<pre>', var_dump( arrayKeyJoin( $arr ) ), '</pre>';

Output:

array(3) {
  [1]=>
  array(1) {
    [0]=>
    int(1)
  }
  [2]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(2)
    [2]=>
    int(2)
  }
  [3]=>
  array(1) {
    [0]=>
    int(3)
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜