I want to add sub arrays to one single array in php [duplicate]

谁说我不能喝 提交于 2019-11-29 03:45:06

问题


i have array like this.........

Array
(
    [0] => Array
        (
            [0] => rose
            [1] => monkey
            [2] => donkey
        )

    [1] => Array
        (
            [0] => daisy
            [1] => monkey
            [2] => donkey
        )

    [2] => Array
        (
            [0] => orchid
            [1] => monkey
            [2] => donkey
        )

)

and i want like this.........

Array
(
    [0] => rose
    [1] => monkey
    [2] => donkey
    [3] => daisy
    [4] => monkey
    [5] => donkey
    [6] => orchid
    [7] => monkey
    [8] => donkey
)

....I used array merge but it's not working because my array generates dymaically and each time shows different arrays. problem is I can't pass arrays dynamically in array_merge() function.It accepts only manually entries of array and not accepts any other variable .function accepts only array.

it works like this ...

$total_data = array_merge($data[0],$data[1],$data[2]);

as each time it generates different numbers of array dynamically so i have to use like this....

$data_array = $data[0],$data[1],$data[2];

 $total_data = array_merge($data_array);

but it shows an error "array_merge() [function.array-merge]: Argument #1 is not an array"......


回答1:


Try this :

$array  = your array

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

Or try this :

function array_flatten($array) {

   $return = array();
   foreach ($array as $key => $value) {
       if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
       else {$return[$key] = $value;}
   }
   return $return;

}

$array  = Your array

$result = array_flatten($array);

echo "<pre>";
print_r($result);



回答2:


try this.....

       $result = array();
        foreach($data  as $dat)

          {
                foreach($dat as $d) 

                 {
                   $result[] = $d;

                 }

           }


来源:https://stackoverflow.com/questions/14951811/i-want-to-add-sub-arrays-to-one-single-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!