在我的./includes/functions.php
中,我具有以下功能
function ck_rank($rank)
{
$strJsonFileContents = file_get_contents("./includes/globals.json");
$status = json_decode($strJsonFileContents, true);
$ranks = array();
foreach ($status as $value) {
array_push($ranks, $value);
}
if (in_array($rank, $ranks)) {
echo "true";
} else {
echo "false" ;
}
}
在我的main.php中,我使用它来检查该函数的返回,如果为true,则显示a;如果为false,则不会显示
if (ck_rank($rank)) { <td>........</td> }
问题是,无论如何,该函数始终返回false。
我真的是json的新手,我敢肯定有更好的方法,但是任何帮助将不胜感激! ty
答案 0 :(得分:2)
您的排名变量
[ { "ranks":"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief" } ]
解码为一个字符串
"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief"
因此,您应该首先将其用逗号分隔。例如,您可以这样做:
function ck_rank($rank)
{
$strJsonFileContents = file_get_contents("./includes/globals.json");
// for your json [ { "ranks":"Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief" } ]
// $ranks variable will contain array:
// [["ranks" => "Director,Asst. Director,Captain,Lieutenant,Chief,Deputy Chief,Dep. Chief"]]
$status = json_decode($strJsonFileContents, true);
$ranks = explode(",", $status[0]['ranks']);
return in_array($rank, $ranks);
}
请注意,我们添加[0],因为在您的json中,它是数组中具有字段ranks
的对象
答案 1 :(得分:1)
问题是您什么都不返回,只是在回显值true或false ...
if ( in_array($rank, $ranks)) { echo "true" ;}
else { echo "false" ; }
应该是
if ( in_array($rank, $ranks)) {
return true;
}
else {
return false;
}
或者您可以将其简化为...
return in_array($rank, $ranks);
答案 2 :(得分:0)
您可以使用此功能:
function ck_rank($rank)
{
$strJsonFileContents = file_get_contents("./includes/globals.json");
$status = json_decode($strJsonFileContents, true);
if (empty($status[0]['ranks'])) {
return false;
}
$rankData = $status[0]['ranks'];
$rankData = explode(',', $rankData);
$ranks = array();
foreach ($rankData as $value) {
array_push($ranks, strtolower(trim($value)));
}
if (in_array(strtolower(trim($rank)), $ranks)) {
echo "true";
} else {
echo "false";
}
}