【问题标题】:php if else statement not echoing elsephp if else 语句不回显 else
【发布时间】:2018-08-28 12:49:58
【问题描述】:

如果没有回显“noname”,则如果存在 xmllang="no",我将尝试回显挪威语。喜欢

000000000121698001,

文本 000000000121699001,无名

但这只会返回所有具有 xmllang="no" 的 productid,而不是打印没有 xmllang="no"productId

XML

<catalog>
<product productid="000000000121698001">
    <displayname xmllang="da">text</displayname>
    <displayname xmllang="fi">text</displayname>
    <displayname xmllang="no">text</displayname>
    <displayname xmllang="sv">text</displayname>    
</product>

<product productid="000000000121699001">
    <displayname xmllang="da">test</displayname>
    <displayname xmllang="x-default">test</displayname>
    <displayname xmllang="sv">test</displayname>
</product>

PHP

foreach ($xml->product as $product) {

    foreach ($product->displayname as $name) {
        switch((string) $name['xmllang']) {
            case 'no':

                echo $product->attributes()->productid. ",";

                if (isset($name)){
                    echo $name. ",", PHP_EOL;
                } else {
                    echo 'noname ,';
                }
                echo "<br>\n";
        }
    }
}

【问题讨论】:

  • isset($name) 在该循环中始终为真,因为该变量在每次迭代时由 foreach 构造设置。
  • 您的开关盒只有一个“否”盒。您可以在底部添加一个default,如果它与前面的任何情况都不匹配,它总是会进入。

标签: php if-statement foreach


【解决方案1】:

我会将其分为两部分:第一,准备数据并找到正确的本地化标签或设置默认值;然后第二次以任何格式输出数据(或理想情况下将$idList 传递给模板)。

<?php
/** @var SimpleXMLElement $xml */

$idList = [];

/* Prepare the data */
foreach ($xml->product as $product) {
    $fallbackLabel = null;

    /* Iterate over the display names */
    foreach ($product->displayname as $name) {
        /* And search for the one in a matching language */
        switch ((string)$name['xmllang']) {
            case 'no':
                $idList[$product->attributes()->productid] = $name;
                break;
            case 'x-default':
                $fallbackLabel = $name;
                break;
        }
    }

    /* If no name in the searched language was found, set a fallback here */
    if (!isset($idList[$product->attributes()->productid])) {
        if (!empty($fallbackLabel)) {
            /* If a label with a language code of "x-default" was found, use that as fallback label */
            $idList[$product->attributes()->productid] = $fallbackLabel;
        } else {
            /* …if not set a static text */
            $idList[$product->attributes()->productid] = 'noname';
        }
    }
}

/* Output the data */
foreach ($idList as $id => $label) {
    echo sprintf("%s,%s<br>\n", $id, $label);
}

【讨论】:

  • 我在 if(!isset) 行周围得到“isset 中的非法偏移类型或为空”。有什么建议么? @feeela
  • @Dengyden 可能是因为 productid 作为 SimpleXML 元素返回。尝试先将其转换为字符串:$productid = (string)$product-&gt;attributes()-&gt;productid; if(isset($idList[$productid])) { … $idList[$productid] = $fallbackLabel; … }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2015-07-07
  • 2021-08-31
  • 2013-12-23
  • 2017-02-05
  • 1970-01-01
  • 2011-05-18
相关资源
最近更新 更多