I need some help with re-working the logic on this php code. What I'd like to do is build in some conditions in this foreach loop to handle empty values, null and give it some default value like 'n/a'. Its using the $class_array to match one of the cases which is read from a text file, but if I don't have either of the statuses, then make it 'n/a'.
I'm just not clear how to construct that. Here is part of the code. I'm thinking, it must be handled within this foreach condition?? Thanks.
$class_array = array(
'Process succeeded' => 'success',
'Process failed' => 'failure',
'Review Logs for status' => 'warn',
'Check for Errors' => 'warn'
);
foreach ($InputFile as $line){
preg_match_all("/([0-9])-([^=]+)=([^;]+);/", $line, $matches, PREG_SET_ORDER);
$LineData = array();
foreach ($matches as $information) {
$LineData[$information[2]] = $information[3];
}
$timestamp = strtotime($LineData["LogDate"]." ".$LineData["StartTime"]);
$LineData['StartTime'开发者_运维知识库] = date("Y-m-d H:i:s",strtotime($LineData['StartTime']));
$LineData['server_url'] = $server_array[$LineData['Server']];
$LineData['status_class'] = $class_array[$LineData['Status']];
$data[$timestamp] = $LineData;
}
Do you mean that $LineData['status_class'] should be set to 'n/a' in case there is no $LineData['Status'] key in $class_array? If so, this should do:
$status_class = 'n/a';
if (array_key_exists($LineData['Status'], $class_array)) {
$status_class = $class_array[$LineData['Status']];
}
$LineData['status_class'] = $status_class;
Use a shorthand conditional assignment.
//Lets assume we're getting some data from a form
$OriginalValue = $_POST['some_user_input'];
//Set a new variable, $NewValue, to the entered data (if available) or a default value.
$NewValue = ( empty($OriginalValue) ) ? 'No data entered' : $OriginalValue;
Simply put any condition (or set of conditions) within the parentheses, and this acts like an if/else. If true, set $NewValue to 'No data entered', else set $NewValue to $OriginalValue.
I think this should work:
if(isset($LineData['status_class'])) {
$LineData['status_class'] array_key_exists($LineData['Status'], $class_array)
? $class_array[$LineData['Status']]
: 'n/a';
}
else
{
$LineData['status_class'] = 'n/a';
}
精彩评论