递减字母值 [英] Decrementing alphabetical values
问题描述
我试图弄清楚如何将数组中的一堆字母值向下移动一个步骤.例如,我的数组包含值("d","e","f","g","h"),而我想将其更改为("c","d","e","f" , G").这是我正在使用的代码:
I'm trying to figure out how to shift a bunch of letter values in an array down one step. For example, my array contains values ("d", "e", "f", "g", "h") and I want to change this to ("c", "d", "e", "f", "g"). Here's the code I'm working with:
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;
}
当我使用正值时,字母会发生变化;但是,负数似乎根本不起作用.
When I use positive values, the letters change; however the negative numbers do not seem to be working at all.
推荐答案
PHP为字符串重载了++
; --
并非如此.您可以使用 chr
, array_map
:
PHP has overloaded ++
for strings; this isn't the case for --
. You can do the same thing with much cleaner code with chr
, ord
, and 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;
}
这是一个演示.请注意,您可能需要添加一种特殊情况来减小a
-我我不确定您要如何处理.
Here's a demo. Note that you may need to add a special case for decrementing a
- I'm not sure how you want to deal with that.
这篇关于递减字母值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!