Home » Php » how to make a new array from an existing array in php?

how to make a new array from an existing array in php?

Posted by: admin February 25, 2020 Leave a comment

Questions:

let’s say if I have an array like this below.

$i = array(
    'arr1'  => array(
        'a11'   => 'ar11',
        'a12'   => 'ar12',
    ),
    'arr2'  => array(
        'a21'   => 'ar21',
        'a22'   => 'ar22',
        'a23'   => 'ar23',
    ),
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

I want a new array that created from this array like the one I mentioned below,

$j = array(
    'a11'   => 'ar11',
    'a12'   => 'ar12',
    'a21'   => 'ar21',
    'a22'   => 'ar22',
    'a23'   => 'ar23',
    'arr3'  => 'arrr3',
    'arr4'  => 'arrr4'
);

sofar I tried extracting the last two elements which aren’t arrays I mention the code below

$ii = $i;
foreach($ii as $k => $v):
    if(is_array($v)):
        unset($ii[$k]);
    endif;
endforeach;

this returns me the last two elements. but the way i tried extracting the other elements looks wired see below.

$i1 = $i['arr1'];
$i2 = $i['arr2'];
$i3 = array_merge($i1, $i2);
$final = array_merge($i3, $j);

this looks simple because it has small amout of elemetns but i have large amount of elements in my project, any other ways to get this output?

How to&Answers:

Can you try this?

$final = [];

foreach($i as $key => $value){
    if(is_array($value){
        $final = array_merge($final, $value);

    }   else{
        $final[$key] = $value;
    }
}

Upd.

@Magnus-Eriksson insists to explain what is going on within loop. At first we check if value is an array or not. If value is an array we merge nested array with (new, created before loop starts) array where we putting our elements. If value isn’t array we just get that value and add it to the final array. There is no magic here. But answer with array_walk_recursive() below is much more elegant but with “magic” within.

Answer:

array_walk_recursive() is what you need:

$a = array(
    'arr1'=> array(
        'a11' => 'ar11',
        'a12' => 'ar12',
    ),
    'arr2'=> array(
        'a21' => 'ar21',
        'a22' => 'ar22',
        'a23' => 'ar23',
    ),
    'arr3' => 'arrr3',
    'arr4' => 'arrr4'
);

$b = array();
array_walk_recursive($a, function($val, $key) use(&$b)
{
    $b[$key] = $val;
});

You can test it here.