how to I update if let say user input chemistry and biology that they want discount price. How do I go to the nested array of user, itemprice to update its value?
[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)
)
I've tried with the solution below, but when I update only chemistry, it will update the biology and mathematics's itemprice together.
Why is that so?
$subject = 'Chemistry';
$index = array_search($subject, $user->iteminfo);
if (false !== $index) {
$user->itemprices[$index] = $newvalue;
}
It works like a charm I rewrite it, you can try it out
$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>";
output
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"
}
}
You are mixing Objects and Arrays, change $user->iteminfo to $user['iteminfo'] and $user->itemprices[$index] to $user['itemprices'][$index] and it would work properly.