php - 为什么如果(条件)不适用于 '{""}''
问题描述
我正在设置一个 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"} 时,输出应该看起来像服务器当前已关闭。
解决方案
可能您应该首先对其进行解码,然后尝试检查 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>";
}
}
推荐阅读
- python - Python 编程反复“被杀”
- python - 使用 /= 规范化变量会引发 ufunc 错误
- javascript - 如何在节点js中为mongodb使用mongoose的填充方法?
- oracle - 如何编写“选择查询”以仅使用一张表查找一个帐户的借方和另一个帐户的贷方之间的差异?
- javascript - 静态方法的第一个参数是指调用它的类吗?
- android - 如何使用正则表达式或其他使用 Firebase ML 的 TextRecognized 从图像中获取文本
- scala - 如何从 ZIO 中的副作用代码访问光纤本地数据
- android - 为 Android 构建 OpenCV 4.0:不能包含
? - python - 通过 Crontab 运行 Python 脚本,但 SQL 数据库未更新
- html - 网站滚动条变小时不可见