更新嵌套数组的多个值

时间:2013-09-20 09:27:40

标签: php arrays

如果让用户输入化学和生物学他们想要折扣价格,如何更新。如何进入用户的嵌套数组,itemprice更新其值?

    [name] => xxxx
    [phone] => xxxxx
    [email]xxxxx
    [itemprices] => Array ( [0] => 1.00 [1] => 1.00 [2] => 1.00)
    [iteminfo] => Array ( [0] => Chemistry [1] => Biology [2] => Mathematics) 
    )

我尝试过下面的解决方案,但是当我只更新化学时,它会一起更新生物学和数学的迭代。

为什么会这样?

$subject = 'Chemistry';
$index = array_search($subject, $user->iteminfo);
if (false !== $index) {
  $user->itemprices[$index] = $newvalue;
}

2 个答案:

答案 0 :(得分:1)

它的作用就像我重写它的魅力,你可以尝试一下

$user = (object) array(
    'name' => 'xxxx',
    'phone' => 'xxxxx',
    'itemprices' => Array (1.00, 1.00, 1.00),
    'iteminfo' => Array ('Chemistry', 'Biology', 'Mathematics') 
    );

echo "<pre>";
var_dump($user);
echo "</pre>";


$newvalue = 2.0;
$subject = 'Chemistry';

$index = array_search($subject, $user->iteminfo);
if (false !== $index) {

  $user->itemprices[$index] = $newvalue;

}

echo "<br><br><pre>";
var_dump($user);
echo "</pre>";

<强>输出

object(stdClass)#21 (4) {
  ["name"]=>
  string(4) "xxxx"
  ["phone"]=>
  string(5) "xxxxx"
  ["itemprices"]=>
  array(3) {
    [0]=>
    float(1)
    [1]=>
    float(1)
    [2]=>
    float(1)
  }
  ["iteminfo"]=>
  array(3) {
    [0]=>
    string(9) "Chemistry"
    [1]=>
    string(7) "Biology"
    [2]=>
    string(11) "Mathematics"
  }
}


object(stdClass)#21 (4) {
  ["name"]=>
  string(4) "xxxx"
  ["phone"]=>
  string(5) "xxxxx"
  ["itemprices"]=>
  array(3) {
    [0]=>
    float(2)
    [1]=>
    float(1)
    [2]=>
    float(1)
  }
  ["iteminfo"]=>
  array(3) {
    [0]=>
    string(9) "Chemistry"
    [1]=>
    string(7) "Biology"
    [2]=>
    string(11) "Mathematics"
  }
}

答案 1 :(得分:0)

您正在混合对象和数组,将$ user-&gt; iteminfo更改为$ user ['iteminfo']和 $ user-&gt; itemprices [$ index]到$ user ['itemprices'] [$ index],它会正常工作。