-2

I have an array as:

    Array
(
    [0] => Array
        (
            [0] => A
            [1] => B
        )

    [1] => C
    [2] => Array
      (
           [0] => D
           [0] => E
      )
)

and I want to convert it like:

Array
(
    [0] => Array
        [0] => A
        [1] => B
        [2] => C
        [3] => D
        [4] => E
)

i.e I want all the values in the first array (irrespective of their indexes) to be aligned in the second array.

User 101
  • 1,351
  • 3
  • 12
  • 18

3 Answers3

0

You need to write a custom script which merge arrays by your logic.

Example:

<?php
$a = [
    ['A', 'B'],
    'C',
    ['D', 'E']
];

$result = [];
foreach ($a as $v) {
    if (is_array($v))
        $result = array_merge($result, $v);
    else
        $result[] = $v;
}

print_r([$result]);
Neodan
  • 5,154
  • 2
  • 27
  • 38
0

You can user this :

$array = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)),0); 

I have copied from here how Turning multidimensional array into one-dimensional array

Md. Nashir Uddin
  • 730
  • 7
  • 20
0

Please try with below code:

$arr = array(
    0 => array("A", "B"),
    1 => "C",
    2 => array("D", "E"),
    );
$result = array();
$response = arrayIndex($arr, $result);

function arrayIndex($arr, $result){
        foreach ($arr as $key => $value) {
            if(is_array($value)){
                $result = $this->arrayIndex($value, $result);
            } else {
                array_push($result, $value);
            }
        }

        return $result;
}

NOTE: This function will convert n level of array elements into a single level array.

halfer
  • 19,824
  • 17
  • 99
  • 186
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57