【问题标题】:Unexpected output when looping through an array遍历数组时出现意外输出
【发布时间】:2012-02-14 15:49:13
【问题描述】:

所以我正在制作一个插件来将 facebook 数据输出到 wordpress 网站,我这样做的方式是通过 json 格式的图形 api 检索 facebook 数据,然后在 php 中解码该 json 数据以获得一个数组,这是当我对 json 解码数据进行变量转储时返回的完整数组:

array
'data' =>

array
  0 => 
    array
      'name' => string '' (length=21)
      'start_time' => string '' (length=19)
      'end_time' => string '' (length=19)
      'location' => string '' (length=11)
      'id' => string '' (length=15)
      'rsvp_status' => string '' (length=9)
  1 => 
    array
      'name' => string '' (length=27)
      'start_time' => string '' (length=19)
      'end_time' => string '' (length=19)
      'id' => string '' (length=15)
      'rsvp_status' => string '' (length=9)
  2 => 
    array
      'name' => string '' (length=35)
      'start_time' => string '' (length=19)
      'end_time' => string '' (length=19)
      'location' => string '' (length=13)
      'id' => string '' (length=15)
      'rsvp_status' => string '' (length=9)
'paging' => 
array
  'previous' => string '' (length=224)
  'next' => string '' (length=211)

现在由于这是一个多维数组,我使用多个 foreach 循环来获取数据,如下所示:

foreach ($data as $data) {
    foreach ($data as $data) { ?>

    <div class="eventSegment">
        <h3><?php echo $data['name']; ?></h3>
        <p><?php echo strstr($data['start_time'], T, true); ?></p>
        <a href="http://www.facebook.com/<?php echo $data['id']; ?>">
            <img src="<?php echo $plugin_dir; ?>/images/rsvpfb.png" alt="RSVP on Facebook" class="RSVPfacebook" />
        </a>    
    </div>

    <?php
    }
}

endif; }  ?>

乱七八糟的我知道;) 但是我总是在最后整理我的代码,反正结果完全没问题,除了两个不应该存在的数据块,$data['name'] 变量对应到他们俩的'h',根本没有日期,他们的id也只是'h',我被这个难住了,不知道从哪里开始寻找解决方案。

【问题讨论】:

    标签: php arrays facebook wordpress


    【解决方案1】:

    你只需要一个foreach:

    假设 $data['data'] 作为开始:

    foreach ($data['data'] as $array_index => $this_data) {
       echo $this_data['name'].'<br />';
    }
    

    【讨论】:

    • 非常感谢,您能解释一下为什么会出现 2 个额外的元素吗?这会很有帮助:)
    • 我猜,随着您的尝试,您在数组中循环了两次,因为您在第一个 foreach 中有 $data,这在您的第二个 foreach 中是相同的。正如@TV productions 所说,不要在 foreach 中再次使用相同的变量名,因为你会用它自己覆盖它。
    【解决方案2】:

    您不能使用相同的变量。使用类似的东西

    foreach($data as $key=>$value) {
     //..etc
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      相关资源
      最近更新 更多