Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Map a PHP Multidimensional Array

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) 
    )
like image 220
random_geek Avatar asked Jun 19 '17 10:06

random_geek


People also ask

How can you create a multidimensional array in PHP?

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 ) );

Is map 2 dimensional array?

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.

Is array multidimensional PHP?

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.

Is PHP array a map?

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.


2 Answers

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

like image 72
Yoshi Avatar answered Oct 20 '22 14:10

Yoshi


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

function myfunction($template)
{
    $template['selected'] = 'null';
    return $template;
}
like image 22
Paul Roefs Avatar answered Oct 20 '22 15:10

Paul Roefs