数组映射PHP多维数组

时间:2021-07-27 21:31:06

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

3 个解决方案

#1


1  

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

#2


1  

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

你没有将$ template作为数组处理,这就是你的函数应该是这样的:

function myfunction($template)
{
    $template['selected'] = 'null';
    return $template;
}

#3


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.

这是工作代码。

#1


1  

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

#2


1  

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

你没有将$ template作为数组处理,这就是你的函数应该是这样的:

function myfunction($template)
{
    $template['selected'] = 'null';
    return $template;
}

#3


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.

这是工作代码。