user1638279
user1638279

Reputation: 523

not able to get the keys of an array having duplicate values in php

after some codings i get a dynamic array like this. it may increase with more values according to data. but this following is a sample.

Array ( 
    [11-23-1] => 5 
    [17-29-2] => 5 
    [9-21-1] => 3 
    [10-52-2] => 5 
    [17-30-2] => 3
  )

after i get this array , i want to get the array in following format - with values of the above array as keys and the keys as value, with unique keys. like -

Array ( 
    5 => Array ( [0] => [11-23-1]
                 [1] => [17-29-2] 
                 [2] => [10-52-2] )

    3 => Array ( [0] =>[9-21-1] 
                 [1] => [17-30-2]) 
  )

how can i do it ??

Upvotes: 1

Views: 85

Answers (3)

Lucas Green
Lucas Green

Reputation: 3959

Here ya go, all packaged up and nice :)

<?
$arr = array (
    '[11-23-1]' => 5,
    '[17-29-2]' => 5,
    '[9-21-1]' => 3,
    '[10-52-2]' => 5,
    '[17-30-2]' => 3,
);

function rotateWithDuplicates($arr) {
    $result = array();

    foreach ($arr as $key => $value) {
        if (!array_key_exists($value, $result)) {
            $result[$value] = array();
        }
        $result[$value][] = $key;
    }

    return $result;
}

var_dump(rotateWithDuplicates($arr));

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39724

reverse

$array = array ('11-23-1' => '5',
                '17-29-2' => '5',
                '9-21-1' => '3',
                '10-52-2' => '5',
                '17-30-2' => '3');

$newArray = array();            
foreach($array as $num => $one){
    $newArray[$one][] = $num;
}

var_export($newArray);

Upvotes: 0

VolkerK
VolkerK

Reputation: 96199

<?php
$source = Array ( 
    '11-23-1' => 5,
    '17-29-2' => 5, 
    '9-21-1' => 3,
    '10-52-2' => 5, 
    '17-30-2' => 3
);


$result = array();
foreach($source as $k=>$v) {
    if ( !isset($result[$v]) ) {
        $result[$v] = array();
    }
    $result[$v][] = $k;
}
var_export($result);

prints

array (
  5 => 
  array (
    0 => '11-23-1',
    1 => '17-29-2',
    2 => '10-52-2',
  ),
  3 => 
  array (
    0 => '9-21-1',
    1 => '17-30-2',
  ),
)

Upvotes: 1

Related Questions