嵌套数组赋值新值

时间:2013-09-19 09:42:36

标签: php

当item等于5时,如何为itemprices赋值。

Object (
    [name] => xxxxx
    [phone] => xxxxxx
    [email] => xxxxxxx
    [items] => Array ( [0] => 0 [1] => 4 [2] => 5 ) 
    [itemprices] => Array ( [0] => 1.00 [4] => 1.00 [5] => 1.00 )
    [itemqtys] => Array ( [0] => 1 [4] => 1 [5] => 1 )
}

3 个答案:

答案 0 :(得分:0)

尝试以下代码:

这里$ array是父数组(Object)

foreach ($array as $key=>$value){
   if($key == "itemprices"){
    // Get inner Array
    $in_arr = $array[$key];
    // Now you can Assign new value
    $newValue = 10;
    $in_arr[5] = $newValue;
   }
}

答案 1 :(得分:0)

你不能使用关联数组吗? 像:

$obj = new stdClass();
$obj->name = 'xxxxx';
$obj->email = 'xxxxx';
$obj->phone = 'xxxxx';
$obj->items = array(
    array( 'quantities' => 1,
           'price' => 1.00, ),
    array( 'quantities' => 1,
           'price' => 1.00, ),
    array( 'quantities' => 1,
           'price' => 1.00, )
);

只是让你的生活更轻松的想法。

答案 2 :(得分:0)

你已经在itemprices内部数组中分配了一个键值5,以便在项目数字等于5时存储价格。在这种情况下,只需查找数组&使用物品编号作为您的钥匙:p

$newprice=1.50;
$arr['itemprices'][5]=$newprice; //$arr['itemprices'] is the array you want to access, and also another array, & the item inside it you want to access have the key as 5 (items number) :p