我有这个多维的输入数组。
$input = array(
array(11, 12, 13, 14, 15),
array(21, 22, 23, 24, 25),
array(31, 32, 33, 34, 35),
array(41, 42, 43, 44, 45),
array(51, 52, 53, 54, 55)
);
我想从此数组中的每个实体中减去1,以便结果变为
$output = array(
array(10, 11, 12, 13, 14),
array(20, 21, 22, 23, 24),
array(30, 31, 32, 33, 34),
array(40, 41, 42, 43, 44),
array(50, 51, 52, 53, 54)
);
我的解决方案
function sub ($a)
{
return $a-1; // what should go here?
}
$output = array_map("sub", $input);
请帮助!!!
答案 0 :(得分:2)
我确信比我聪明的人可以想到使用循环的另一种方法,但如果你不想要array_map()
我只能考虑使用另一个foreach()
:
<?php
function subtractor($v)
{
$sub = 1;
return ((int)$v - (int)$sub);
}
function annon($v)
{
return array_map("subtractor",$v);
}
$arr = array_map("annon", $input);
print_r($arr);
?>
给你:
Array
(
[0] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
[1] => Array
(
[0] => 20
[1] => 21
[2] => 22
[3] => 23
[4] => 24
)
[2] => Array
(
[0] => 30
[1] => 31
[2] => 32
[3] => 33
[4] => 34
)
[3] => Array
(
[0] => 40
[1] => 41
[2] => 42
[3] => 43
[4] => 44
)
[4] => Array
(
[0] => 50
[1] => 51
[2] => 52
[3] => 53
[4] => 54
)
)
答案 1 :(得分:1)
您可以尝试的另一种方式
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array(
array(11, 12, 13, 14, 15),
array(21, 22, 23, 24, 25),
array(31, 32, 33, 34, 35),
array(41, 42, 43, 44, 45),
array(51, 52, 53, 54, 55)
);
for ($row = 0; $row < 5; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 5; $col++) {
$cars[$row][$col] = $cars[$row][$col] - 1;
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>
运行代码
答案 2 :(得分:1)
array_map
函数正在使用一个暗淡的数组,你需要执行两次,参见代码
<?php
$input = array(
array(11, 12, 13, 14, 15),
array(21, 22, 23, 24, 25),
array(31, 32, 33, 34, 35),
array(41, 42, 43, 44, 45),
array(51, 52, 53, 54, 55)
);
$op = array_map(function($v){
return array_map(function($v1){return $v1 - 1;}, $v);
}, $input);
print_r($op);