首页 > 解决方案 > 为什么如果(条件)不适用于 '{""}''

问题描述

我正在设置一个 PHP 代码,它从 Bash 中获取一些信息并将它们放入 PHP 中。我的 If 语句不会对我写的或从 bash 中得到的内容进行排序。

这适用于 Linux 上的服务器 Apache2。我试图将我想在我的条件中使用的字符串放在一个变量中。

GameToken = `grep "Matching server game" "${FactorioServerLogPath}" 2> /dev/null | awk '{print $7}' | tail -1 | tail -c +2 | head -c -2`;

$GameState = `curl -s -X GET -H "Content-type: application/json" -H "Accept: application/json" "https://multiplayer.factorio.com/get-game-details/$GameToken"`;

if ( $GameState != '{"message":"no game for given game_id"}' ) {
  echo "<h2> The Server is up and running </h2>";
} else {
  echo "<h2> The Server is currently turned off </h2>";
}

当变量 $GameState 不像 {"message":"no game for given game_id"} 时,输出应该看起来像服务器当前已关闭。

标签: phpif-statement

解决方案


可能您应该首先对其进行解码,然后尝试检查 if 条件:

例如:

$arr = json_decode($GameState, true);

if(array_key_exists('message', $arr) && $arr['message'] == 'no game for given game_id'){
     //do what you want
}

或者做得更好:

$arr = json_decode($GameState, true);

if(array_key_exists('message', $arr)){
    if($arr['message'] != 'no game for given game_id'){
        echo "<h2> The Server is up and running </h2>";
    }else{
        echo "<h2> The Server is currently turned off </h2>";
    }
}

推荐阅读