1

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

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

我该怎么做 ??

4

3 回答 3

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',
  ),
)
于 2012-08-31T09:52:05.620 回答
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);
于 2012-08-31T09:53:04.213 回答
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));
于 2012-08-31T09:54:51.233 回答