7

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) 
    )
random_geek
  • 345
  • 2
  • 8
  • 23

3 Answers3

10

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

Yoshi
  • 54,081
  • 14
  • 89
  • 103
1

you do not handle $template as an array, this is what your function should look like:

function myfunction($template)
{
    $template['selected'] = 'null';
    return $template;
}
Paul Roefs
  • 368
  • 2
  • 3
  • 13
0

You can achieve in some sort of way mentioned below,

function array_push_assoc(&$array, $key, $value){
    foreach($array as $k => $v)
        $array[$k][$key] = $value;
 return $array;
}
$result = array_push_assoc($template, 'selected','null');
print_r($result);

Adding to every index of associative array.

Here is working code.

Rahul
  • 18,271
  • 7
  • 41
  • 60