Home > Software design >  How to combine array in php to dynamically?
How to combine array in php to dynamically?

Time:02-12

i have code like this

$a =[
      [1,2],
      [4,6],
      [10,24]
    ];

i want a output like this

    Array
    (
      [0] => 1
      [1] => 2
      [2] => 4
      [3] => 6
      [4] => 10
      [5] => 24
    )

and i use code like this

print_r(array_merge($a[0],$a[1],$a[2]));

if a have code like this and have more data

    Array
   (
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 4
            [1] => 6
        )
    [2] => Array
        (
            [0] => 10
            [1] => 24
        )
       .
       .
       .
     [60] => Array
            [0] => 67
            [1] => 8
     ) 

writing like this is not good

print_r(array_merge($a[0],$a[1],$a[2],...,...,...,$a[58]));

how to use array_merge in dinamic in there ?

CodePudding user response:

You can use the following function.

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

CodePudding user response:

Try:

function my_array_merge($array1, $array2) {
    foreach ($array2 as $key => $val) {
        if (is_array($val)) {
            $array1[$key] = my_array_merge($array1[$key], $array2[$key]);
        } else {
            if (is_numeric($key)) {
                $array1[] = $array2[$key];
            } else {
                $array1[$key] = $array2[$key];
            }
        }
    }
    return $array1;
}

As far as I know, the above exactly works like array_merge(), but merges arrays inside it:

$arr1 = array(array("a"));
$arr2 = array(array("b"));

will become:

Array (
        [0] => Array (
                [0] => a
                [1] => b
        )
)

CodePudding user response:

u can use this:

$a =[
      7,
      [1,2],
      [4,6],
      [10,24],
      [[30,40],[2,9]]
    ];

function mrg($array){
    $out = [];
    foreach($array as $b){
        if(is_array($b))
            $out = array_merge($out, mrg($b));
        else
            $out[] = $b;
    }
    return $out;
}

print_r(mrg($a));

CodePudding user response:

$result = array_reduce($a, fn($carry, $item) => array_merge($carry, $item), []);
  • Related