在PHP三元情况下设置变量值

时间:2017-08-15 12:10:14

标签: php ternary

我试图在后一种情况下使用三元输出做两件事。

我的问题是在增加错误计数后,在后一种情况下为变量设置文本值。

我尝试了一些事情,这是两次尝试,但这些都在设置$errors_log值时失败。

Q值。如何在三元输出中设置变量值。

$errors_v=0;
if (validate_username() == false ? null : $errors_v++ && $errors_log='username invalid');

if ($errors_v != 0) {
    echo $errors_log;
}

function validate_username() {
    return true;
}

$errors_v=0;
$errors_log[];
if (validate_username() == false ? null : $errors_v++ && $errors_log[]='username invalid');

if ($errors_v != 0) {
    var_dump($errors_log);
}

function validate_username() {
    return true;
}

3 个答案:

答案 0 :(得分:1)

我会像下面那样做我的三元组,然后检查$errors_log[] = validate_username() === false ? null : 'username invalid'; if (!empty($errors_log)) { foreach($errors_log as $error) { echo $error; } } function validate_username() { return true; } 是否为空,如果不是,请打印错误。

$errors_log

如果需要有一个计数器,即使我真的建议你依靠if (!validate_username()) { $errors_log[] = 'username invalid'; $errors_v++; } 数组,你也可以这样做:

{{1}}

答案 1 :(得分:1)

你正在混合"手写"和"速记"条件语法。

您的模糊函数名称加上其返回值会令人困惑/不直观。我建议重命名你的函数或者反转它返回的布尔值。

始终努力使用DRY and DAMP编码实践。

代码后半部分的方法看起来比第一部分更好。
如果你要生成一系列错误,不要为增加一个计数器而烦恼,只需在你计算时计算数组愿望。

我认为没有必要用速记条件来理解您的代码。

代码:(Demo

function bad_username(){  // new meaningful function name
    return true;
}

$errors_log=[];  // declare the variable as an array
if(bad_username()){
    $errors_log[]='username invalid';  // push the value
}

if(sizeof($errors_log)){  // count elements in array, if 1 or more display them
    var_export($errors_log);
}else{
    echo "No Error";
}

输出:

array (
  0 => 'username invalid',
)

答案 2 :(得分:0)

您无法在三元情况下执行两项操作。您可以检查$errors_log empty是否$errors_v以及if语句中是否为if (validate_username() == false ? null : $errors_log='username invalid'); if (!empty($errors_log)) { $errors_v++; echo $errors_log; } function validate_username() { return true; } 增量,如下所示:

// Work Order


// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";

function addDates() {
  var date = new Date(); // your form date
  var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
  var days = 5; //No of days you want to add
  date.setDate(date.getDate());
  var counter = 0;
  if (days > 0) {
    while (counter < days) {
      date.setDate(date.getDate() + 1);
      var check = date.getDay();
      var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
      if (check != 0 && check != 6 && holidayCheck == -1) {
        counter++;
      }
    }
  }
  Logger.log(date) //for this example will give 08/16/2017
  return date;
}

function createNewDoc(values) {
//Get information from form and set as variables
  var email_address = "";
  var job_name = values[1];
  var ship_to = values[11];
  var address = values[12];
  var order_count = values[7];
  var program = values[2];
  var workspace = values[3];
  var offer = values[4];
  var sort_1 = values[5];
  var sort_2 = values[6];
  var image_services = values[9];
  var print_services = values[10];
  var priority = values[13];
  var notes = values[14];
  var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
  var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");

  // Get document template, copy it as a new temp doc, and save the Doc's id
  var copyId = DriveApp.getFileById(docTemplate)
    .makeCopy(docName + ' for ' + job_name)
    .getId();
  // Open the temporary document
  var copyDoc = DocumentApp.openById(copyId);
  // Get the document's body section
  var copyBody = copyDoc.getActiveSection();

  // Replace place holder keys,in our google doc template  
  copyBody.replaceText('keyJobName', job_name);
  copyBody.replaceText('keyShipTo', ship_to);
  copyBody.replaceText('keyAddress', address);
  copyBody.replaceText('keyOrderCount', order_count);
  copyBody.replaceText('keyProgram', program);
  copyBody.replaceText('keyWorkspace', workspace);
  copyBody.replaceText('keyOffer', offer);
  copyBody.replaceText('keySort1', sort_1);
  copyBody.replaceText('keySort2', sort_2);
  copyBody.replaceText('keyImageServices', image_services);
  copyBody.replaceText('keyPrintServices', print_services);
  copyBody.replaceText('keyPriority', priority);
  copyBody.replaceText('keyNotes', notes);
  copyBody.replaceText('keyDate', formattedDate);
  copyBody.replaceText('keyDue', expirationDate);

  // Save and close the temporary document
  copyDoc.saveAndClose();

  // Convert temporary document to PDF by using the getAs blob conversion
  var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");

  // Attach PDF and send the email
  var subject = "New Job Submission";
  var body = "Here is the work order for " + job_name + "";
  MailApp.sendEmail(email_address, subject, body, {
    htmlBody: body,
    attachments: pdf
  });

  // Move file to folder
  var file = DriveApp.getFileById(copyId);
  DriveApp.getFolderById("").addFile(file);
  file.getParents().next().removeFile(file);
}

function printGoogleDocument(copyId, docName) {
  // For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
  var ticket = {
    version: "1.0",
    print: {
      color: {
        type: "STANDARD_COLOR"
      },
      duplex: {
        type: "NO_DUPLEX"
      },
    }
  };

  var payload = {
    "printerid": "",
    "content": copyId,
    "title": docName,
    "contentType": "google.kix", // allows you to print google docs
    "ticket": JSON.stringify(ticket),
  };

  var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
    method: "POST",
    payload: payload,
    headers: {
      Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
    },
    "muteHttpExceptions": true
  });

  // If successful, should show a job here: https://www.google.com/cloudprint/#jobs

  response = JSON.parse(response);
  if (response.success) {
    Logger.log("%s", response.message);
  } else {
    Logger.log("Error Code: %s %s", response.errorCode, response.message);
  }
  return response;
}

// When Form Gets submitted
function onFormSubmit(e) {
  var values = e.values;
  createNewDoc(values);
  printGoogleDocument(copyId, docName);
}