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)
)
You create a multidimensional array using the array() construct, much like creating a regular array. The difference is that each element in the array you create is itself an array. For example: $myArray = array( array( value1 , value2 , value3 ), array( value4 , value5 , value6 ), array( value7 , value8 , value9 ) );
Map Method for 2-dimensional Arrays Also called a map within a map: Sometimes you'll come across a multidimensional array -- that is, an array with nested arrays inside of it.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. The dimension of an array indicates the number of indices you need to select an element.
Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
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
you do not handle $template as an array, this is what your function should look like:
function myfunction($template)
{
$template['selected'] = 'null';
return $template;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With