3

我是 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',
        );

     );

非常感谢...

4

3 回答 3

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
)

如果您想要每个键的唯一值,例如,如果您想避免aequaling 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);
于 2012-12-08T05:36:16.287 回答
2

我自己会去的:

    $result = array_merge_recursive($a, $b, $c);
    foreach($result as $k => $v) $result[$k] = array_unique($v);
    print_r($result);
于 2012-12-08T07:15:18.783 回答
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
 

希望这可以帮助。

于 2012-12-08T05:57:59.930 回答