将多个数组从一个结果合并到PHP中的单个数组中

时间:2013-03-06 16:57:09

标签: php mysql arrays

我真的很抱歉打扰你,我已经有一个问题,我一直试图解决这个问题已经有一段时间了。我已经完成了一些研究并找到了像array_merge这样的东西,但它似乎没有帮助我。

无论如何,足够的华夫饼干。我有一个看起来像这样的查询结果:

Array
(
    [0] => STRINGA
)
Array
(
    [0] => STRINGA
    [1] => STRINGB
)
Array
(
    [0] => STRINGA
    [1] => STRINGB
    [2] => STRINGC
)
Array
(
    [0] => STRINGD
    [1] => STRINGC
    [2] => STRINGA
    [3] => STRINGB
    [4] => STRINGE
    [5] => STRINGF
)

如何将上述内容合并到一个数组中,以使结果看起来更像:

Array
(
    [0] => STRINGA
    [1] => STRINGB
    [2] => STRINGC
    [3] => STRINGD
    [4] => STRINGE
    [5] => STRINGF
)

可以忽略原始数组中的重复项,因为我只需要将字符串放入新数组中一次。

任何帮助都会受到大力赞赏。

谢谢。

EDITED:这是从数据库中得出结果的代码块:

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    foreach($row as $splitrow) {
        if(NULL != $splitrow) {
            $therow = explode(';',$splitrow);
        }   
        //print_r retrieves result shown above
        print_r($therow);                                    
    }
}

2 个答案:

答案 0 :(得分:5)

$bigarray = array(
  array (
    0 => 'STRINGA',
  ),
  array (
    0 => 'STRINGA',
    1 => 'STRINGB',
  ),
  array(
    0 => 'STRINGA',
    1 => 'STRINGB',
    2 => 'STRINGC',
  )
);


$result = array_values( 
    array_unique( 
        array_merge( $bigarray[0], $bigarray[1], $bigarray[2] ) 
    ) 
);  
// array_merge will put all arrays together, including duplicates
// array_unique removes duplicates
// array_values will sort out the indexes in ascending order (1, 2, 3 etc...)

答案 1 :(得分:0)

    $bigarray = array();

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {

            foreach($row as $value){

                if($value != NULL){
                    $therow = explode(';',$value);

                    foreach($therow as $key=>$values){

                        //push the value into the single array 'bigarray'
                        array_push($bigarray, $values); 

                    }
                }                                    
            }           
    }
    //remove duplicates 
    $uniquearray = array_unique($bigarray);
    //reset key values
    $indexedarray = array_values($uniquearray);

    print_r($indexedarray);

感谢所有帮助过的人,非常感谢!