【问题标题】:PHP connecting to WCF Service parsing return dataPHP连接到WCF服务解析返回数据
【发布时间】:2011-02-20 17:18:19
【问题描述】:

我在解析 WCF Web 服务返回的数据时遇到问题。

Web 服务正在传回一个字符串数组,此数据被放入一个 StdClass 对象,我遇到的问题是数据会根据是否存在 1 个或多个对象而变化。

我从未处理过 stdclass 对象,我不确定该怎么做。

以下是我目前使用的代码,$containers 是网络服务调用的返回值。

<ul>
<?php var_dump($containers)?>
<?php foreach($containers as $item):?>
<li>
<?php 
echo $item->string;
?>
</li>
<?php endforeach;?>
</ul>

如果只返回 1 个值,则以下代码可以正常工作并显示返回的容器名称。 如果返回的值超过 1 个,则 $item->string 变为 Array。无论如何确定 stdclass 包含哪些值?

只有 1 个容器的 var_dump

object(stdClass)[13]
public 'GetContainersResult' => 
object(stdClass)[14]
public 'string' => string 'container1' (length=10)

具有超过 1 个容器的 var_dump

object(stdClass)[13]
public 'GetContainersResult' => 
object(stdClass)[14]
public 'string' => 
array
0 => string 'container1' (length=10)
1 => string 'container2' (length=10)

提前致谢,

马特

【问题讨论】:

    标签: php stdclass


    【解决方案1】:

    您可以使用is_array($item-&gt;string) 来检查您是否有一个数组,然后对其进行适当的处​​理。根据您的代码,我认为这样的事情可能对您有用。

    <?php var_dump($containers)?>
    <ul>
    <?php foreach($containers as $item):
             if(is_array($item->string)):
                foreach($item->string as $subitem):
                    <li class="subitem"><?php echo $subitem; ?></li>
                <?php 
                endforeach;
             else: ?>
            <li><?php echo $item->string; ?></li>
              <?php 
              endif;
          endforeach;    
    ?>
    </ul>
    

    【讨论】:

    • 感谢帮助,需要将 foreach 语句更改为 'foreach($item->string as $subitem):' 并将 li 语句更改为
    • 并且需要在 foreach 语句之后添加一个 php 结束标记,但它现在可以工作了,再次感谢
  • 很高兴能帮上忙。感谢您的反馈,我将代码更新为正确。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签