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...**

);

では、次のようにそれらを 1 つの配列にマージするにはどうすればよいですか。

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
)

aキーごとに一意の値が必要な場合、たとえばequalingを避けたい場合は、次の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 に答える