2012-06-25 100 views
0

這是我的數組,我想添加一些元素,使其像2個數組添加項目到多維數組中的for循環

1)

array(7) { 
    [0] => array(3) { 
    ["name"] => string(9) "airG Chat" 
    ["product_id"] => int(2469) 
    ["price"] => string(4) "0.00" 
    } 

    [1] => array(3) { 
    ["name"] => string(9) "PingChat!" 
    ["product_id"] => int(7620) 
    ["price"] => string(4) "0.00" 
    } 
    [2] => array(3) { 
    ["name"] => string(25) "MobiEXPLORE Zagreb County" 
    ["product_id"] => int(8455) 
    ["price"] => string(4) "0.00" 
    } 
} 

添加項目後,應像這樣,我嘗試使用每個功能,但沒有工作。 2)

array(7) { 
    [0] => array(3) { 
    ["name"] => string(9) "airG Chat" 
    ["product_id"] => int(2469) 
    ["price"] => string(4) "0.00" 
    ["description"] => string(23) "this is the custom test" 
    ["brief_description"] => string(23) "this is the custom test" 
    } 

    [1] => array(3) { 
    ["name"] => string(9) "PingChat!" 
    ["product_id"] => int(7620) 
    ["price"] => string(4) "0.00" 
    ["description"] => string(23) "this is the custom test" 
    ["brief_description"] => string(23) "this is the custom test" 
    } 
    [2] => array(3) { 
    ["name"] => string(25) "MobiEXPLORE Zagreb County" 
    ["product_id"] => int(8455) 
    ["price"] => string(4) "0.00" 
    ["description"] => string(23) "this is the custom test" 
    ["brief_description"] => string(23) "this is the custom test" 
    } 
} 

回答

3

使用foreach參考(&):

foreach($data as &$datum) { 
    $datum["description"] = "this is the custom test"; 
    $datum["brief_description"] = "this is the custom test"; 
} 

如果你不希望使用&to avoid this problem),你可以做

foreach($data as $i => $datum) { 
    $data[$i]["description"] = "this is the custom test"; 
    $data[$i]["brief_description"] = "this is the custom test"; 
} 
2

如果您使用的foreach,並希望改變原來的數組,你需要添加&

foreach ($arr as &$item) { 
    $item["description"] = "this is the custom test"; 
    $item["brief_description"] = "this is the custom test"; 
} 
+0

酷,不知道它,謝謝! :) – arik