目前我有这个
// display all address with their associated phone numbers
foreach ($data->address as $address) {
if ($address->fullAddress) echo $address->fullAddress;
if ($address->phones->PhoneNumber) echo $address->phones->PhoneNumber);
}
但是如果不满足上述条款中的陈述,我需要添加它作为替代
// display all phone numbers if there is not an address
if ($data->relatedPhone) echo $data->relatedPhone;
如果没有达到任何条款,我根本不想显示任何内容。那么如何将两者结合起来呢?
答案 0 :(得分:2)
这是一个快速简单的解决方案:
$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;
答案 1 :(得分:0)
您可以执行else if
而不是其他if
:
if (foo) {
echo "bar";
} else if (foo2) {
echo "bar2";
} else {
echo "foobar";
}
仅当所有其他else
语句评估为false时,才会运行最后一个if
。
所以在你的情况下,我会试试这个:
// 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;
}
}
答案 2 :(得分:0)
您需要将逻辑结构化为更容易为您处理的if语句:
// 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;
}
}
答案 3 :(得分:0)
您可以创建一个标志来表示是否满足至少一个条件。
$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;
}