如何分离数组中重复值的键

时间:2013-07-18 09:56:55

标签: php arrays multidimensional-array logic

我有一个动态的$ my_Array。我该怎么做才能根据$ my_Array获得$ Final_array。

    $my_Array = array(  
                ['arm'] => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                ['min'] => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                ['msk'] => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                ['con'] => 'c72a7fb8-308a-482a-96d5-7a7853e16c49',
                ['ref'] => 'c72a7fb8-308a-482a-96d5-7a7853e16c49',
             ) 


   $Final_array = array
                (   'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6' => 'arm, min, msk',
                    'c72a7fb8-308a-482a-96d5-7a7853e16c49' => 'con, ref'
                )

3 个答案:

答案 0 :(得分:3)

$my_Array = array(  
                'arm' => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                'min' => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                'msk' => 'cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6',
                'con' => 'c72a7fb8-308a-482a-96d5-7a7853e16c49',
                'ref' => 'c72a7fb8-308a-482a-96d5-7a7853e16c49',
             ) ;
$data = array();
foreach( $my_Array as $key => $value) {
    if(isset( $data[ $value ] )) {
        $data[ $value ] = $data[ $value ] .', '.$key;
    } else {
        $data[ $value ] = $key;
    }
}

希望以上代码可以帮助您。

答案 1 :(得分:1)

$Final_array = array();               
foreach($my_Array as $key => $value){
 if(array_key_exists($value, $Final_array)){

  $Final_array[$value] = $Final_array[$value]. ", ".$key;

 }else{

  $Final_array[$value] = $key;

 }
}
print_r($Final_array);        
?>

输出:

Array
(
    [cc9f8eb4-e29f-44b4-8dcd-ac08e9b1faa6] => arm, min, msk
    [c72a7fb8-308a-482a-96d5-7a7853e16c49] => con, ref
)

答案 2 :(得分:0)

我尝试用一​​个循环来做这个并且失败了,但是希望它对你好。

$new = array();
foreach ($my_Array as $key => $val) {
   $new[$val][] = $key;
}

foreach ($new as $key => $val) {
   $new[$key] = implode(", ". $val);
}