如果Else Echo JSON数组检查


If Else Echo JSON array check

我有一个JSON数组,我从每个$vars中提取值。JSON中的数据将是我正在寻找的一些关键词。我有一个单独的if else,看起来像:

(演示目的)

if( $FullName == $Data[$c]['manager'] $FullName == $Data[$c]['leader'] || $FullName == $Data[$c]['helper']) {
    $cheapLabor = 'NO';
} else {
    $cheapLabor = 'YES';
}

这很好,但是,现在我想更具体地定义状态点上的一些if else点,这些点将代表他们的雇佣状态。每个Emp状态都基于一个组。

我需要它从食物链的顶部检查,然后向下检查status = x。如果是,则$cheapLabor = 'y'; else $cheapLabor = 'z';

我试着做了,但似乎做不到。以下是我正在使用的内容:

$repData = json_decode($json, TRUE);    
$c = 0;
$var = $repData[$c]['column'];
if($FullName == $repData[$c]['ceo']) {
    $groups = '[13]';
} else {
    $groups = '[5]';
}                                                   
if($FullName == $repData[$c]['director']) {
    $groups = '[10]';
} else {
    $groups = '[5]';
}
if($FullName == $repData[$c]['regional']) {
    $groups = '[9]';
} else {
    $groups = '[5]';
}   
if($FullName == $repData[$c]['project_manager']) {
    $groups = '[8]';
} else {
    $groups = '[]';
}   
if($FullName == $repData[$c]['team_leader']) {
    $groups = '[6]';
} else {
    $groups = '[5]';
}   
if($FullName == $repData[$c]['rae']) {
    $groups = '[5]';
} else {
    $staus = '[5]';
}

Shomz回答部分工作。。。

$groups = '[4]'; // new hire group default, to be overwritten if a user has the correct title within Table.
$roleGroups = array(
                    'regional' => '[7]',
                    'team_leader' => '[6]',
                    'RAE' => '[5]'                  
                    );  
foreach ($roleGroups as $role => $groups) {  // go through all the Position Titles
    if ($FullName == $repData[$c][$role]) { // see if there's a match
        $repGroup = $groups;                  // if so, assign the group
    } 
 }  

它正确地设置了team_leader和regional,但其他任何操作都只将其设置为regional group。

只是意识到它实际上改写了价值。

您的代码正在覆盖每个if语句中的$groups。您可能想在switch/case语句中重写它,默认值为[5]

假设第一个if为真,那么$FullName == $repData[$c]['ceo']为真,$groups变为[13]。在下一行中,有两个选项:

  • 要么一个人是董事(要么是首席执行官,但这并不重要,见下文原因)
  • 或者某人不是董事(可能是CEO)

这两种情况下,$groups将获得值[10][5],这意味着无论上面的语句内部发生了什么,该语句都将覆盖它。因此,只有最后一个if语句才能产生您可能期望的结果。


"每个角色只有一个组"

在这种情况下,一个简单的switch/case语句将起作用:

switch($FullName){
  case ($repData[$c]['ceo']):
    $groups = '[13]';
    break;                                          
  case ($repData[$c]['director']):
    $groups = '[10]';
    break;
  // etc... for other roles
  default: 
    $groups = '[5]';
    break;
}   

或者,您可以更简单地使用关联数组将角色与组号相结合。例如:

$roleGroups = array('ceo' => '[13]', 'director' => '[15]', etc);

然后简单地看看是否有匹配:

$groups = '[5]'; // default, to be overwritten if a role is found below
foreach ($roleGroups as $role => $group) {  // go through all the groups
    if ($FullName == $repData[$c][$role]) { // see if there's a match
        $groups = $group;                   // if so, assign the group
    }
 }

希望这是有道理的。无论哪种方式,如果找到角色,$groups将具有该角色的编号,否则为5。