-3

I'm working on a project, where I get an Array like this

Array
(
    [0] =>  Array
        (
            [0] => value1
            [1] => value2
            [2] => value3        
        )
    [1] => Array
        (
            [0] => value4
            [1] => value5
            [2] => value6    
        )
    [2] => Array
        (
            [0] => value7
            [1] => value8
            [2] => value9     
        )
)

I want to merge it like this

Array
(
  [0] => value1
  [1] => value2
  [2] => value3        
  [3] => value4
  [4] => value5
  [5] => value6    
  [6] => value7
  [7] => value8
  [8] => value9           
)

Im using php 5.6, any help would be greatly appreciated!

Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42
Arsalan
  • 461
  • 3
  • 12
  • and what exactly is your problem? you mentioned the function to solve it already in your question title, and i guess you know about loops (especially foreach)? – Franz Gleichmann Oct 20 '16 at 09:54
  • From where you have created the 1st array.show us the case. – Dipanwita Kundu Oct 20 '16 at 09:55
  • array_merge does not give me what I need, its mentioned in the question what I get and what i need, I want to avoid the use of foreach loop, can it be done with any array utlility function ? otherwise I will have no choice but to do it manually with foreach! – Arsalan Oct 20 '16 at 09:57
  • a foreach is the most straightforward method to solve this - why exactly don't you like it? and all the built-in functions do nothing different internally, anyway. to process all elements, you have to *look at all elements*, and foreach is the best way to do this. – Franz Gleichmann Oct 20 '16 at 10:01

1 Answers1

3

You can try this function:

function array_flatten($array)
{
    if (!is_array($array)) {
        return false;
    }

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

    return $result;
}
xpuc7o
  • 333
  • 3
  • 15