在嵌套中向数组添加值

时间:2012-09-15 15:41:26

标签: php arrays multidimensional-array foreach

我正在尝试使用下面的代码向数组中添加值,但它似乎只会导致将1个项目(循环中的最后一个)添加到数组中。

$awin_products = array();

foreach($awinprices as $value){
foreach($value as $obj){        
    $awin_products[name] = (string)$obj->sName;
    $awin_products[imageUrl] = (string)$obj->sAwThumbUrl;
    }
}
print_r($awin_products); 

这可能很容易解决,但到目前为止我还没有找到答案。

编辑:我正在寻找这个输出:

Array
(
    [0] => Array
        (
            [name] => Item 1 Name
            [imageUrl] => http://example.com/item1.jpg
        )
    [1] => Array
        (
            [name] => Item 2 Name
            [imageUrl] => http://example.com/item2.jpg
        )
    [2] => Array
        (
            [name] => Item 3 Name
            [imageUrl] => http://example.com/item3.jpg
        )
    [3] => Array
        (
            [name] => Item 4 Name
            [imageUrl] => http://example.com/item4.jpg
        )
)

2 个答案:

答案 0 :(得分:4)

你在每次运行中都覆盖了相同的值:

foreach($value as $obj){         
    $awin_products[name] = (string)$obj->sName; 
    $awin_products[imageUrl] = (string)$obj->sAwThumbUrl; 
} 

你需要改变你写的地方;也许是这样的:

$i = 0;
foreach($awinprices as $value){ 
    $awin_products[$i] = array();
    foreach($value as $obj){  
        $awin_products[$i][]['name'] = (string)$obj->sName; 
        $awin_products[$i][]['imageUrl'] = (string)$obj->sAwThumbUrl; 
    } 
    $i++;
}

答案 1 :(得分:2)

您需要关注

$awin_products = array();
$i = 0;
foreach($awinprices as $value){
    foreach($value as $obj){        
        $awin_products[$i]['name'] = (string)$obj->sName;
        $awin_products[$i]['imageUrl'] = (string)$obj->sAwThumbUrl;
        $i++;
    }
}

然后你会得到这样的结构:

Array
(
            [0] => Array
                (
                    [name] => name
                    [imageUrl] => url
                )
            [1] => Array
                (
                    [name] => name1
                    [imageUrl] => url1
                )
)