无法在php中获取具有重复值的数组的键

时间:2012-08-31 09:47:05

标签: php arrays associative-array

经过一些编码后我得到了这样的动态数组。根据数据,它可能会随着更多的值而增加。但以下是一个样本。

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

我得到这个数组之后,我想以下列格式获取数组 - 上面数组的值为键,键为值,带有唯一键。喜欢 -

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

我该怎么办?

3 个答案:

答案 0 :(得分:1)

<?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);

打印

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',
  ),
)

答案 1 :(得分:0)

逆转

$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);

答案 2 :(得分:0)

在这里,所有打包并且很好:)

<?
$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));