循环访问JSON值并将其添加到变量但保持为null

时间:2017-03-11 22:52:41

标签: php

我有一个代码,它通过JSON并获取color值并将其添加到$color变量。下一行代码将推送添加数据到数组,但color保持为null。我用echo测试并且颜色代码出来了,就好像我将它添加到变量中它是null。可能是什么问题?

        $color = '';
        foreach($descriptions['tags'] as $tag){
            $color = $tag['color']; //Adding it to the variable
        }
        $inventoryItems['items'][] = array(
            'id' => $assets['assetid'],
            'name' => $descriptions['market_hash_name'],
            'price' => $price,
            'icon' => $descriptions['icon_url'],
            'color' => $color //Gives null here
        );

1 个答案:

答案 0 :(得分:0)

如果您仔细查看数据,并非所有[descriptions]数组都包含[color],那么您必须更具体地找到正确的出现。

foreach($descriptions['tags'] as $tag){

    if ( isset($tag['color']) ) {
        $inventoryItems['items'][] = array(
                                        'id' => $assets['assetid'],
                                        'name' => $descriptions['market_hash_name'],
                                        'price' => $price,
                                        'icon' => $descriptions['icon_url'],
                                        'color' => $tag['color']
                                    );
    }
}

另请注意,[description]的某些出现有$tag[color]次出现Select Col_Group, Average_1, Average_1*2 as Twice_Average_1 from ( Select Avg(Col_1) AS Average_1, Col_Group From Table ) as tmp 。请注意确保在这种情况下您想要做什么。