-4

I have an php array like:-

Array
(
   [colors] => Array
      (
        [0] => white
        [1] => Yellow
        [2] => Black
        [3] => white
        [4] => Array
            (
                [0] => white
                [1] => Black
            )

        [5] => Array
            (
                [0] => white
                [1] => Black
            )
        [6] => white
        [7] => red
    )

)

Now I want Output like:

Array
(
   [colors] => Array
    (
      [0] => white
      [1] => Yellow
      [2] => Black
      [3] => white
      [4] => white
      [5] => Black
      [6] => white
      [7] => Black
      [8] => white
      [9] => red
   )
)

Means if array element has array value then it will be moved to parent. I don't want child layer. Please suggest how can I achieve

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Ankita Agrawal
  • 504
  • 8
  • 28

4 Answers4

3

You can use array_splice() like so:

for ($i=0; $i<count($arr['colors']); $i++) {
    if (is_array($arr['colors'][$i])) {
        array_splice($arr['colors'], $i, 1, $arr['colors'][$i]);
    }
}

Or might as well create a function for it to make a one-liner call:

function flattenArray($arr) {
    for ($i=0; $i<count($arr); $i++) {
        if (is_array($arr[$i])) {
            array_splice($arr, $i, 1, $arr[$i]);
        }
    }
    return $arr; // flattened array
}

$result = flattenArray($arr['colors']);
Rax Weber
  • 3,730
  • 19
  • 30
0

Please check this

  foreach($myarray as $array){
        foreach($array as $val){
            $array_1[] = $val;
        }
    }
AftabHafeez
  • 173
  • 13
0

Here is an way.

$someArray = ['YOUR_ARRAY_HERE']; 
$newArray = [];

foreach ($someArray as $value) {
    if(is_array($value)) {
        foreach ($value as $innerValue) {
            array_push($newArray, $innerValue);
        }
        continue;
    }

    array_push($newArray, $value);

}

print_r($newArray);
Mahfuzul Alam
  • 3,057
  • 14
  • 15
0

Try this, best and optimal solution

$new_array['colors'] = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$list = iterator_to_array($it,false);
$new_array['colors'] = $list;

print_r($new_array);

DEMO

Dave
  • 3,073
  • 7
  • 20
  • 33