在查询结果中将不同的数组合并为一个数组

时间:2012-12-08 05:30:25

标签: php arrays multidimensional-array

我是PHP和CodeIgniter的新手。所以我有一个数据库查询结果,如下所示:

Result = array(

A = array(
        [a]=>'1',
        [b] =>'2',
     );

B = array(
        [a] =>'1',
        [b] =>'3',
     );

C = array(
        [a] =>'1',
        [b] =>'4',
     );

**and more...**

);

那么如何将它们合并为一个这样的数组:

Result = array(

     Z = array(

        [a] =>'1',
        [b] => array(

               [0] =>'2',
               [1] =>'3',
               [2] =>'4',
        );

     );

非常感谢你......

3 个答案:

答案 0 :(得分:2)

$A = array( 'a' => '1', 'b' => '2', 'c' => '3');
$B = array( 'a' => '1', 'b' => '3', 'd' => '4');
$C = array( 'a' => '1', 'b' => '4', 'c' => '5');

$Result = array($A, $B, $C);
$Z = array();
foreach ($Result as $set) {
    foreach ($set as $key => $val) {
        if (isset($Z[$key])) {
            if (is_array($Z[$key])) {
                $Z[$key][] = $val;
            } elseif ($Z[$key] != $val) {
                $Z[$key] = array($Z[$key], $val);
            }
        } else {
            $Z[$key] = $val;
        }
    }
}

print_r($Z);

<强>输出

Array
(
    [a] => 1
    [b] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 4
        )

    [c] => Array
        (
            [0] => 3
            [1] => 5
        )

    [d] => 4
)

如果您想要每个键的唯一值,例如,如果您想避免a等于array(1, 1, 2),那么您可以这样做:

$Z = array();
foreach ($Result as $set) {
    foreach ($set as $key => $val) {
        if (!isset($Z[$key])) {
            $Z[$key] = array();
        }
        $Z[$key][] = $val;
    }
}

foreach($Z as $k => $v) {
    $newv = array_unique($v);
    if (count($newv) == 1) {
        $Z[$k] = $newv[0];
    } else {
        $Z[$k] = $newv;
    }
}

print_r($Z);

答案 1 :(得分:2)

我自己也会这样做:

    $result = array_merge_recursive($a, $b, $c);
    foreach($result as $k => $v) $result[$k] = array_unique($v);
    print_r($result);

答案 2 :(得分:0)

尝试

 
$final_array = array();
foreach ($Result as $key=>$value){
  foreach ($value as $inner_key=>$inner_value){
     $final_array[] = $inner_value; //this adds all the values into a single array 
  }
}

$final_array = array_unique($final_array); // this removes all duplicates
 

修改

 
$final_array = array();
foreach ($Result as $key=>$value){
  foreach ($value as $inner_key=>$inner_value){
     $final_array[$inner_key] = $inner_value; //this adds all the values into a single array; duplicate keys will simply replace one another during the iteration 
  }
}

//$final_array = array_unique($final_array); // this part is no longer required
 

希望这有帮助。