array_flip to print duplicate values in comma separated format

后端 未结 2 1181
我寻月下人不归
我寻月下人不归 2021-01-14 10:19

I\'m trying to use array_flip to print duplicate values in a comma separated format

$a=array(\"a\"=>\"red\",\"b\"=>\"green\",\"c\"=>\"b         


        
相关标签:
2条回答
  • 2021-01-14 10:38

    array_flip will not give your expected output. Instead of this you can write your custom function like:

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

    Will give output:

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

    0 讨论(0)
  • 2021-01-14 10:48

    You need to make your function along with array_flip like as

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

    Output :

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

    Demo

    0 讨论(0)
提交回复
热议问题