0

如果让说用户输入他们想要折扣价的化学和生物学,我该如何更新。我如何去嵌套的用户数组 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;
}
4

2 回答 2

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"
  }
}
于 2013-09-20T09:47:18.200 回答
0

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

于 2013-09-20T12:43:52.477 回答