我有一个简单的数组,其所有键都用整数编号:
$ArrOne = array (
"-5" => "x",
"-4" => "b",
"-3" => "s",
"-2" => "e",
"-1" => "a",
"0" => "d",
"1" => "k",
"2" => "l",
"3" => "w",
"4" => "y",
"5" => "c"
);
而且,我有一个整数变量,例如:$VarKey
。
现在,我想对所有键($ArrOne
)进行简单求和,其值为$VarKey
。输出数组是:$ArrTwo
;例如:
$VarKey = -1;
,$ArrTwo
将是:$ArrTwo = array ( "-6" => "x", "-5" => "b", "-4" => "s", "-3" => "e", "-2" => "a", "-1" => "d", "0" => "k", "1" => "l", "2" => "w", "3" => "y", "4" => "c" );
如果$VarKey = 0;
,$ArrTwo
将不会更改。
如果$VarKey = +1;
,$ArrTwo
将是:
$ArrTwo = array ( "-4" => "x", "-3" => "b", "-2" => "s", "-1" => "e", "0" => "a", "1" => "d", "2" => "k", "3" => "l", "4" => "w", "5" => "y", "6" => "c" );
如何用 PHP 语言解决这个问题?
答案 0 :(得分:1)
最简单的方法是使用foreach
迭代输入数组并构建一个新数组:
$outArray = array();
foreach ($inpArray as $key => $value) {
$outArray[$key + $MyInteger] = $value;
}
// That's all, folks!