我试图弄清楚如何将数组中的一堆字母值向下移动一步.例如,我的数组包含值("d","e","f","g","h"),我想将其更改为("c","d","e","f ", "G").这是我正在使用的代码:
function move_up_left($x) {
if($x['orientation'] == "down") {
foreach($x[0] as &$value) {
$value = --$value;
}
} else {
foreach($x[1] as &$value) {
$value = --$value;
}
}
return $x;
}
Run Code Online (Sandbox Code Playgroud)
当我使用正值时,字母会改变; 但负数似乎根本不起作用.
Ry-*_*Ry- 15
PHP已经++为字符串重载了; 事实并非如此--.你可以做同样的事情更清洁的代码chr,ord以及array_map:
function decrementLetter($l) {
return chr(ord($l) - 1);
}
function move_up_left($x) {
if($x['orientation'] === 'down') $arr = &$x[0];
else $arr = &$x[1];
$arr = array_map('decrementLetter', $arr);
return $x;
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示.请注意,您可能需要添加一个特殊情况以进行递减a- 我不确定您要如何处理它.
小智 6
如果您需要减少类似Excel的变量(“ A”,“ AA”,...),这就是我要使用的函数。它不适用于特殊字符,但不区分大小写。如果尝试递减“ a”或“ A”,则返回null。
function decrementLetter($char) {
$len = strlen($char);
// last character is A or a
if(ord($char[$len - 1]) === 65 || ord($char[$len - 1]) === 97){
if($len === 1){ // one character left
return null;
}
else{ // 'ABA'--; => 'AAZ'; recursive call
$char = decrementLetter(substr($char, 0, -1)).'Z';
}
}
else{
$char[$len - 1] = chr(ord($char[$len - 1]) - 1);
}
return $char;
}
Run Code Online (Sandbox Code Playgroud)