合并数组元素

时间:2012-12-01 05:22:40

标签: php arrays

Array
(
[0] => Array
    (
        [id] => 1
        [name] => abc
        [email] => abc@abc.com
        [hardware_type] => keybord
    )

[1] => Array
    (
        [id] => 1
        [name] => abc
        [email] => abc@abc.com
        [hardware_type] => mouse
    )

)

和结果需要像这样

Array
(
[0] => Array
    (
        [id] => 1
        [name] => abc
        [email] => abc@abc.com
        [hardware_type] => keybord , mouse
    )

 )

2 个答案:

答案 0 :(得分:0)

考虑到:

$a; // array input 1
$b; // array input 2

这是您正在寻找的功能:

function datFunction($a, $b) {
    $c = array(); // array output
    foreach ($a as $key => $value) {
        if (array_key_exists($key, $b) and $b[$key] != $value) {
            $c[$key] = array($value, $b[$key]);
            // or $c[$key] = "$value , {$b[$key]}";
        } else {
            $c[$key] = $value;
        }
    }
    foreach ($b as $key => $value) {
        if (!array_key_exists($key, $c)) {
            $c[$key] = $value;
        }
    }
    return $c;
}

答案 1 :(得分:0)

$array1 = array(array
    (
        'id' => 1,
        'name' =>' abc',
        'email' => 'abc@abc.com',
        'hardware_type' => 'keybord'
    ),array
    (
        'id' => 1,
        'name' => 'abc',
        'email' => 'abc@abc.com',
        'hardware_type' => 'mouse'
    )
    ,array
    (
        'id' => 2,
        'name' => 'abc2',
        'email' => 'abc@abc.com',
        'hardware_type' => 'mouse'
    )
);

function mergarrays($array){            
        $arrayout = array();
        for($i = 0; $i < count($array); ++$i){
        foreach($array[$i] as $key => $value){
                if(array_key_exists($key,$arrayout)){
                    if( strpos($arrayout[$key],$value) == null){
                        if($arrayout[$key] != $value)
                            {
                                if(!in_array($value,explode(',',$arrayout[$key]))){
                                    $arrayout[$key] = $arrayout[$key] . ','.$value;
                                    }                           
                            }                       
                        }                   
                }else
                {
                    $arrayout[$key] = $value ;
                }
            }
        }
        return $arrayout;
        }
print_r(mergarrays($array1));