使用Array Map函数映射PHP多维数组

7

有一个多维数组

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

1
这个问题没有问题。 - quinz
你阅读了 array_map() 的文档吗? - axiac
3个回答

11
您需要在回调函数中将值添加到每个给定的数组中,例如:
<?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


1
你不能将$template作为一个数组处理,这是你的函数应该像这样的形式:
function myfunction($template)
{
    $template['selected'] = 'null';
    return $template;
}

0

你可以通过以下方式之一来实现:

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

给关联数组的每个索引添加内容。

这里是可用的代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接