PHP-如何使用特定模式打印字符串? (单词搜索网格)

时间:2019-01-28 11:42:28

标签: php

我需要帮助来打印带有特定单词的字符串。有点困惑,应该显示SOFTWARESENI。有人可以给我解决这个问题的想法吗?

$string = "
S Q X C P R T M
R O M S P H P D E V C I
X N F P L Z M H R K N J
P D S T X R N D G E B Y
J Z D G W C W E S X
M B S C N A P E Q
Y Z D G Q V R D S";

$string_to_array = explode("\n", $string);
$i = 0;
foreach ($string_to_array as $key => $value) {
    $per_string = explode(" ", $value);
    $hasil[] = $per_string[$i]; 
    $i++;
}

这是我的结果。


    [0] => S
    [1] => O
    [2] => F
    [3] => T
    [4] => W
    [5] => A
    [6] => R

输出必须是SOFTWARESENI。

2 个答案:

答案 0 :(得分:1)

向下循环一次,向上一次循环,通过比较$ col和该行中的项目计数来跟踪是否碰到“墙”。

// Preperations
$arr = explode("\n", $string);
foreach($arr as &$val){
    $val = explode(" ", $val);
}

// start at:
$col=0;

for($row=0; $row<count($arr); $row++){
    if($col >= count($arr[$row])) break; // stop if we reach the end
    $word[] = $arr[$row][$col];
    $col++;
}

// loop rows backwards
for($row=$row-2; $row>0; $row--){
    if($col >= count($arr[$row])) break; // stop if we reach the end
    $word[] = $arr[$row][$col];
    $col++;
}

var_dump($word);

输出:

array(12) {
  [0]=>
  string(1) "S"
  [1]=>
  string(1) "O"
  [2]=>
  string(1) "F"
  [3]=>
  string(1) "T"
  [4]=>
  string(1) "W"
  [5]=>
  string(1) "A"
  [6]=>
  string(1) "R"
  [7]=>
  string(1) "E"
  [8]=>
  string(1) "S"
  [9]=>
  string(1) "E"
  [10]=>
  string(1) "N"
  [11]=>
  string(1) "I"
}

https://3v4l.org/IJg9d

答案 1 :(得分:0)

使用一个循环执行此操作的另一种方法

$string_to_array = explode("\n", $string);
$length  = count($string_to_array); // count number of element in array

$j = 0;

// loop twice through $string_to_array once forward and once backward
for($k=0;$k<(($length-1)*2);$k++){

    // explode each element of $string_to_array by index
    $per_string = explode(" ", $string_to_array[$j]);

    // check if indexed element exists and add it to result array
    $hasil[] = isset($per_string[$k]) ? $per_string[$k] : ''; 

    // check if we reached at the end of $string_to_array array
    if($k >= ($length-1)){
        // if we are at end start moving backward
        $j--;
    }else{
       // else move forward
        $j++;
    }
}

echo "<pre>";
print_r($hasil);
echo "</pre>";

输出:

Array
(
    [0] => S
    [1] => O
    [2] => F
    [3] => T
    [4] => W
    [5] => A
    [6] => R
    [7] => E
    [8] => S
    [9] => E
    [10] => N
    [11] => I
)