开发者

foreach within if /else

Currently I have this

// display all address with their associated phone numbers
    foreach ($data->address as $address) {
      if ($address->fullAddress) echo $address->fullAddress;
      if ($address->phones->Pho开发者_JAVA技巧neNumber) echo $address->phones->PhoneNumber);
    }

but I need to add this as an alternative if the statements in the above clause are not met

// display all phone numbers if there is not an address
    if ($data->relatedPhone) echo $data->relatedPhone;

If none of the clauses are met I want nothing to display at all. So how can I combine the two?


here is a quick simple solution:

$addrfound=false;
foreach ($data->address as $address) {
  if ($address->fullAddress) { echo $address->fullAddress; $addrfound=true; }
  if ($address->phones->PhoneNumber) { echo $address->phones->PhoneNumber); $addrfound=true; } 
}

if (!$addrfound)
    if ($data->relatedPhone) echo $data->relatedPhone;


You can do an else if instead of another if:

if (foo) {
  echo "bar";
} else if (foo2) {
  echo "bar2";
} else {
  echo "foobar";
}

The last else is run only if all other if statements evaluate to false.

So in your case, I'd try this:

// display all address with their associated phone numbers
    foreach ($data->address as $address) {
      if ($address->fullAddress) {
        echo $address->fullAddress;
      } else if ($address->phones->PhoneNumber) {
        echo $address->phones->PhoneNumber;
      } else if ($data->relatedPhone) {
        echo $data->relatedPhone;
      }
    }


You need to structure your logic into if statements that are more easy to deal for you:

// display all address with their associated phone numbers
foreach ($data->address as $address) 
{
    $hasAddress = (bool) $address->fullAddress;
    $hasPhone = (bool) $address->phones->PhoneNumber;
    $isAddress = ??; # add your decision here, I can't see you specified it in your question.

    if ($hasAddress) echo $address->fullAddress;
    if ($hasPhone) echo $address->phones->PhoneNumber;

    // display all phone numbers if there is not an address
    if (!$isAddress) {
        if ($data->relatedPhone) echo $data->relatedPhone;
    }
}


You could create a flag to signal whether at least one of the conditions is met.

$flag = 0;
if (condition_1) {
  echo $output_1;
  $flag = 1;
}

if (condition_2) {
  echo $output_2;
  $flag = 1;
}

if (!$flag && condition_3) {
  echo $output_3;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜