Php 更新嵌套数组的可变值

Php 更新嵌套数组的可变值,php,arrays,Php,Arrays,我如何更新,如果让用户输入化学和生物,他们想要折扣价格。如何转到user,itemprice的嵌套数组来更新其值 [name] => xxxx [phone] => xxxxx [email]xxxxx [itemprices] => Array ( [0] => 1.00 [1] => 1.00 [2] => 1.00) [iteminfo] => Array ( [0] => Chemistry [1]

我如何更新,如果让用户输入化学和生物,他们想要折扣价格。如何转到user,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) 
    )
我尝试过下面的解决方案,但当我只更新化学时,它会同时更新生物学和数学的itemprice

为什么会这样

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

它就像一个符咒,我重写它,你可以试试

$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>";

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

请提供有关所需逻辑的更多数据。现在还不清楚,我觉得很清楚。OP希望更新某个索引的itemprices(如果该索引存在于数组中)。您似乎在混合对象和数组。提供完整的$user数组或对象。我不知道其复杂性,但如果您可以将数组更新为
['item']=>数组('chemistry'=>1.00,…)
。您可以很容易地管理这些数据。您可以重建这些数据的结构吗@里奇有个好主意:)
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"
  }
}