array_flip以逗号分隔格式打印重复值

时间:2015-09-30 11:11:29

标签: php arrays

我正在尝试使用array_flip以逗号分隔格式打印重复值

$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"blue");
$flip=array_flip($a);
print_r($flip);

我的输出是:

Array ( [red] => a [green] => b [blue] => d )

但我的预期输出是:

Array ( [red] => a [green] => b [blue] => c,d)

我如何获得该输出?

2 个答案:

答案 0 :(得分:5)

您需要将您的功能与array_flip一样使用

$array = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"blue");

$res = array_flip($array);

foreach ($res as $k => $v)
    $res[$k] = implode(", ", array_keys($array, $k));
print_r($res);

输出

Array
(
    [red] => a
    [green] => b
    [blue] => c, d
)

Demo

答案 1 :(得分:0)

array_flip不会提供您的预期输出。您可以编写自定义函数,而不是这样:

$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"blue");
$flip = array_flip_custom($a);

print_r($flip);
function array_flip_custom($a){
    $flip = array();
    foreach($a as $index=>$key){
        if($flip[$key]){
            $flip[$key] .= ','.$index;
        } else {
            $flip[$key] = $index;
        }
    }
    return $flip;
}

会给出输出:

  

数组([红色] => a [绿色] => b [蓝色] => c,d)