0

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

5 Answers 5

2

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()

Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

1

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

Comments

1

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".

Comments

0

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)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.