简体   繁体   中英

Merge multple arrays from one result into a single array in PHP

I'm really sorry to bug you, put I've got a problem that I've been trying to resolve for quite some time now. I've done some research and have found things like array_merge but it doesn't appear to help me.

Anyway, enough waffle. I have a result of a query that looks something like this:

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
)

How can I combine the above into one array so that the result will look more like:

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

Duplicates in the original arrays can be ignored as I only need the string to be placed into the new array once.

Any help would be massively appreciated.

Thank you.

EDITED: This is the block of code that brings out the result from the database:

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);                                    
    }
}
$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...)
    $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);

Thanks to all of those that helped, much appreciated!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM