【问题标题】:Foreach in foreach alternativeforeach 中的 foreach 替代方案
【发布时间】:2018-07-02 11:57:57
【问题描述】:

我一直在试图弄清楚如何在没有数量 $item x 数量 $iteminfo 的情况下在 foreach 中拥有一个 foreach。 看看吧。

$inventory = file_get_contents("https://steamcommunity.com/profiles/".$_SESSION['steamid']."/inventory/json/730/2");

$myarrayInv = json_decode($inventory, true);  
if(isset($myarrayInv['rgDescriptions']))
{
    if(isset($myarrayInv['rgInventory'])) {
        foreach($myarrayInv['rgDescriptions'] as $item) {
            foreach($myarrayInv['rgInventory'] as $iteminfo) {
            echo "<div class='item'><img class='item' src='https://steamcommunity-a.akamaihd.net/economy/image/".$item['icon_url']."' height='90' width='120'/><span class='caption'>".$item['name']." | ".$iteminfo['id']."</span></div>&nbsp;"; 
        }
    }
}

此代码支持显示项目,当我删除“$iteminfo”的循环时,项目的数量显示正确。像这样。

第 1 项,第 2 项,第 3 项,第 4 项。

当我将 forloop 添加回来时,它会变成这样。

item1,item1,item1,item1,item2,item2,item2,item2,item3,item3,item3,item3,item4 item4 item4 item4。

我不知道有什么好的解决方案,有什么想法吗?

编辑: 也许我对我想要实现的目标不够清楚,看。 $item 数组不包含 itemid,但 $iteminfo 包含 itemid。

我希望 itemid 与 itemname 和图片一起显示,如果我在 while 循环中有一个 while 循环,这将起作用。

【问题讨论】:

  • 发布一个示例数组。
  • 你想得到什么结果?
  • 已编辑答案..
  • 我还是不明白。这两个数组有什么关系?
  • 如果$myarrayInv['rgDescriptions'][index] 对应于$myarrayInv['rgInventory'][index] 中的同一个项目,那么您可以使用 for 循环并通过索引访问这两个数组

标签: php foreach


【解决方案1】:

每个 rgDescription 都由 rgInventory 中的 [classid_instanceid] 键入,而不是直接的相似索引。所以这对你来说可能会更好(我使用我的个人 Steam 库存进行了测试,似乎显示图标和名称):

$json = file_get_contents('https://steamcommunity.com/profiles/'. $_SESSION['steamid'] .'/inventory/json/730/2');

$data = json_decode($json, true);
foreach($data['rgInventory'] as $inv) {
    $desc = $data['rgDescriptions'][ $inv['classid'] .'_'. $inv['instanceid'] ];

    echo "<div class='item'><img class='item' src='https://steamcommunity-a.akamaihd.net/economy/image/". $desc['icon_url'] ."' height='90' width='120'/><span class='caption'>". $desc['name'] ." | ". $inv['id'] ."</span></div>&nbsp;";
}

【讨论】:

    【解决方案2】:

    只需使用一个循环,然后在两个数组中使用相同的索引。

    foreach ($myarrayInv['rgDescriptions'] as $index => $item) {
        $iteminfo = $myarrayInv['rgInventory'][$index];
        echo "<div class='item'><img class='item' src='https://steamcommunity-a.akamaihd.net/economy/image/".$item['icon_url']."' height='90' width='120'/><span class='caption'>".$item['name']." | ".$iteminfo['id']."</span></div>&nbsp;";
    }
    

    您还可以考虑重新组织数据。不要使用两个数组,而是使用带有 rgDescriptionsrgInventory 键的单个数组。

    【讨论】:

    • 我在$iteminfo = $myarrayInv['rgInventory'][$index]; 行收到了这个错误Undefined index: $index in
    • 你知道是什么原因造成的吗?
    • 您使用的是上面写的确切代码吗?错误提示并非如此。
    • 我不是,但我已尝试复制确切的代码,但错误仍然存​​在。
    • 我赞成这一点,因为它是许多用途的合理逻辑。 (但使用 steam 愚蠢的 json 逻辑,索引引用很奇怪)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2021-05-16
    • 2018-01-04
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多