数组映射 PHP 多维数组

问题描述 投票:0回答:4

有一个多维数组

$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 arrays multidimensional-array array-map
4个回答
12
投票

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

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


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

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

这是工作代码


0
投票

使用箭头函数语法和“数组联合运算符”将静态/硬编码关联元素附加到二维数组的每一行。

代码:(演示

$array = [
    ['id' => 352, 'name' => 'a'],
    ['id' => 438, 'name' => 'b'],
    ['id' => 351, 'name' => 'c'],
];

var_export(
    array_map(
        fn($row) => $row + ['selected' = null],
        $array
    )
);
© www.soinside.com 2019 - 2024. All rights reserved.