Array Map a PHP Multidimensional Array

random_geek picture random_geek · Jun 19, 2017 · Viewed 9k times · Source

Have a multidimensional array

$template=Array (
 [0] => Array ( [id] => 352 [name] => a ) 
 [1] => Array ( [id] => 438 [name] => b ) 
 [2] => Array ( [id] => 351 [name] => c ) 
               ) 

and an array map function

function myfunction()
{

return "[selected]=>null";
}
print_r(array_map("myfunction",$template));

which results in

Array ( 
   [0] => [selected]=>null 
   [1] => [selected]=>null 
   [2] => [selected]=>null
    )

how do I map the array to get this result instead

Array (  
        [0] => Array ( [id] => 352 [name] => a [selected] => null)  
        [1] => Array ( [id] => 438 [name] => b  [selected] => null)  
        [2] => Array ( [id] => 351 [name] => c  [selected] => null) 
    )

Answer

Yoshi picture Yoshi · Jun 19, 2017

You need to add the value to each given array (inside the callback), like:

<?php

$in = [
    [ 'id' => 352, 'name' => 'a' ],
    [ 'id' => 438, 'name' => 'b' ],
    [ 'id' => 351, 'name' => 'c' ],
];

$out = array_map(function (array $arr) {
    // work on each array in the list of arrays
    $arr['selected'] = null;

    // return the extended array
    return $arr;
}, $in);

print_r($out);

Demo: https://3v4l.org/XHfLc