Array 映射一个 PHP 多维数组

Array Map a PHP Multidimensional Array

有一个多维数组

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

和数组映射函数

function myfunction()
{

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

这导致

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

我如何映射数组以获得此结果

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

您需要将值添加到每个给定数组(在回调内),例如:

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

演示:https://3v4l.org/XHfLc

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

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

您可以通过下面提到的某种方式实现,

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

添加到关联数组的每个索引。

这里正在工作code