我有这个数组:
Array
(
[grp] => Array
(
[1] => Array
(
[firstname] => 5
[lastname] =>
[email] =>
[username] =>
[password] =>
)
............
)
预期必须是:
Array
(
[grp] => Array
(
[1] => Array
(
[firstname] => required
[lastname] => required
[email] => required
[username] => required
[password] => required
)
............
)
我已尝试array_walk
和array_map
,但它仍然给我这个输出:
Array
(
[0] => Array
(
[0] => Array
(
[firstname] => required
)
[1] => Array
(
[lastname] => required
)
[2] => Array
(
[email] => required
)
[3] => Array
(
[username] => required
)
[4] => Array
(
[password] => required
)
)
这是我的代码:
$a = [];
for($i = 1; $i <= count($count); $i++){
$a[] = $count[$i];
}
function map($a)
{
$newArr = [];
foreach($a as $key => $val)
{
$newArr[] = [$key => 'required'];
}
return $newArr;
}
function walk($a, $key)
{
$key = 'required';
return $key;
}
print_r(array_walk($a, 'walk'));
print_r(array_map('map', $a, $a));
帮助我摆脱这种情况。谢谢!
答案 0 :(得分:1)
$array['grp'][1] = array_fill_keys(array_keys($array['grp'][1]), 'required');
如果[1]
中的$array['grp']
以上,则循环:
foreach ($array['grp'] as &$values) {
$values = array_fill_keys(array_keys($values), 'required');
}
或者,当然,map
:
$array['grp'] = array_map(function (array $values) {
return array_fill_keys(array_keys($values), 'required');
}, $array['grp']);
如果您基本上想要替换任意嵌套数组中的每个 leaf ,那么array_walk_recursive
:
array_walk_recursive($array, function (&$value) { $value = 'required'; });
答案 1 :(得分:1)
使用嵌套循环
foreach ($array as $i => $subarray1) {
foreach ($subarray1 as $j => $subarray2) {
foreach (array_keys($subarray2) as $k) {
$array[$i][$j][$k] = 'required';
}
}
}
答案 2 :(得分:0)
foreach ( $array["grp"] as $key => $val ) {
$array["grp"][$key] = "required";
}