我有这段代码:
$mainArray = Array(
[0] => Array
(
[0] => 06
)
[1] => Array
(
[0] => 15
)
)
$array1 = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20");
$array2 = array_reverse($array1);
我想用$ array2的值递归替换$ mainArray的值(例如,当$ mainArray中的值等于15时替换为5,6替换为14。
我试过了:
foreach($mainArray $k1 => $value1){
foreach($value1 as $k2 => $value2){
$value2 = str_replace($array1,$array2,$value2);
echo $value2;
}
}
但不能正常工作。
答案 0 :(得分:0)
在第一个数组中查找索引,并从第二个数组中取值
$value2 = $array2[array_search($value2, $array1)];
或者算法总是相同的
$max = 20;
$value2 = $max - $value2;
答案 1 :(得分:0)
您可能不需要其他阵列来执行此操作。如果我正确理解替换策略,您可以通过从20中减去原始值来获得替换值,从而以数学方式进行。
$replaced = array_map(function($x) {
return array(20 - $x[0]);
}, $mainArray);