【问题标题】:Can't figure out how to make this PHP Array table不知道如何制作这个 PHP 数组表
【发布时间】:2015-12-15 17:31:35
【问题描述】:

我似乎不知道如何打印一个漂亮的有序表。

我希望最多有 7 列,它可以根据数组的大小生成所需的行数。该数组是通过一个可以随时更新的 URL。 (它是 Steam 上的玩家库存)。

$id = $steamprofile['steamid'];
$key = 'XXXXXXXXXXXXXXXXXXXX';
if($id != null){
  $inv = file_get_contents('http://steamcommunity.com/profiles/'.$id.'/inventory/json/730/2');
  $inventory = json_decode($inv, true);

  $price = file_get_contents('values/response.json');
  $value = json_decode($price, true);

  foreach ($inventory['rgDescriptions'] as $rgDescription) {                                
    for($i = 0; sizeof($rgDescription['market_name']) > $i; $i++){
      if(isset($rgDescription['market_name'])){
        print '<td><img src="https://steamcommunity-a.akamaihd.net/economy/image/'.$rgDescription['icon_url'].'" alt="'.$rgDescription['market_name'].' width="80" height="75"></td>';
      }
    }
  }
}

数组位于here,如果您需要查看它。

我可以打印出表格,但它总是重复我不想要的项目。那么我该如何解决呢?非常感谢任何建议。

【问题讨论】:

  • JSON 完全不可读,因为浏览器会逃避缩进。您可以在此处粘贴代码格式,在您的问题中,它的相关部分吗?
  • 首先,打印你的表格: echo '
    ' , print_r($inventory , true) , '
    ';看看你的代码是否与你尝试的匹配

标签: php html arrays multidimensional-array html-table


【解决方案1】:

您只需要计算列数:

$max = 7;
$col = 1;
for(...) {
   if ($col == 1) {
      echo '<tr>'; // start new row if on column #1
   }
   echo '<td><img etc....'; // output a column
   if ($col == $max) {
     echo '</tr>'; // if column $max was just output, end the row
     $col = 0; // reset column count, 0 to account for ++ coming up next
   }
   $col++;
}

【讨论】:

  • 太简单了,谢谢,由于某种原因,我无法理解它。
【解决方案2】:

"market_name" 不是数组,而是 one 的元素。如果你 count 它(与 sizeof 相同),它将返回 1,因为它只分配了一个值。也就是说,您的行for($i = 0; sizeof($rgDescription['market_name']) &gt; $i; $i++)for($i = 0; 1 &gt; $i; $i++) 相同,总是返回相同的结果。

foreach 播放重复部分,然后你会得到一个带有相同线条的大桌子。

建议:

foreach ($inventory['rgDescriptions'] as $rgDescription) {                                
    foreach ($rgDescription as $rg) {
        if(isset($rg['market_name'])) {
            print('
                <td>
                    <img src="https://steamcommunity-a.akamaihd.net/economy/image/'
                    .$rgDescription['icon_url'].
                    '" alt="'.$rgDescription['market_name'].
                    ' width="80" height="75"></td>');
        }
    }
}

【讨论】:

  • 感谢您指出这一点,它基本上是从我网站的另一部分复制粘贴,我从那里拉出阵列并没有仔细查看它。不需要第二个 foreach。
猜你喜欢
  • 2017-10-19
  • 1970-01-01
  • 2016-06-19
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多