Php 如果下一个条目是整数,则在数组中应用函数(连接一个有效的 FEN 字符串)

Php apply function in array if next entry is integer (Concatenate a valid FEN string)

正在尝试构建有效的 FEN string

给定这个 8*8 数组示例,表示一个棋盘,(“1”是空方块):

$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]]

原地,这是位置:

我要查找的有效结果是:

rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR

现在我的输出是:

rnbqkbnr/pppppppp/11111111/11111111/1111P111/11111111/PPPP1PPP/RNBQKBNR

显然,数组中的任何整数条目都应该与下一个条目相加,前提是下一个条目是整数,如果是这样,下一个条目应该被丢弃直到结束.

通过迭代数组,我不确定如何以简单的方式在此处应用 array_walk() or array_map() 之类的东西。也许一个简单的字符串操作就足够了?

  $FEN = "";
  for ($i = 0;$i < 8;$i++){
    for ($j = 0;$j < 8;$j++){
      if ($checkerboard[$i][$j] === "1"){
        if ($checkerboard[$i][$j + 1] === "1"){
           /* How to iterate till the end */
           $FEN .= (int)$checkerboard[$i][$j] + (int)$checkerboard[$i][$j+1];
        }
      } else {
        $FEN .= $checkerboard[$i][$j];
      }      
    }
    $FEN .= "/";
  }

有什么见解吗?

在线示例: https://3v4l.org/tuqqo

$checkerboard = [["r","n","b","q","k","b","n","r"],["p","p","p","p","p","p","p","p"],["1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1"],["1","1","1","1","P","1","1","1"],["1","1","1","1","1","1","1","1"],["P","P","P","P","1","P","P","P"],["R","N","B","Q","K","B","N","R"]];

$parts =  array();
foreach ($checkerboard as $innerArray) {
    $num = null;
    $str = '';
    foreach($innerArray as $innerval){
        if(is_numeric($innerval)){
            $num += (int) $innerval;
        }
        else{
            if(!is_null($num)){
                $str .=$num;
                $num = null;
            }
            $str .=$innerval;
        }
    }
    if(!is_null($num)){
        $str .=$num;
    }
    array_push($parts,$str);
}
$result = implode('/',$parts);

以上代码将生成所需的输出并将其存储在 $result 中。