Reputation: 443
I have an array $users
as such:
[0] => Array (
[userid] => 1
[score] => 9.9
)
[1] => Array (
[userid] => 2
[score] => 9
)
For each user, I then retrieve items and store them into an array, $results
:
foreach ($users as $user) {
$items = getItems($user['userid']);
$results[] = $items:
}
The $results
array ends up looking like this:
[0] => Array (
[0] => Array (
[itemid] => 1
[rating] => 9.9
)
[1] => Array (
[itemid] => 2
[rating] => 9
)
)
[1] => Array (
[0] => Array (
[itemid] => 3
[rating] => 8.5
)
[1] => Array (
[itemid] => 2
[rating] => 7.5
)
)
What I would like to do, is weigh the item rating with the user score. So, for each item, the rating would be multiplied by user score * 0.1.
What I've tried is this:
foreach ($users as $user) {
$items = getItems($user['id']);
foreach ($items as $item) {
$item['rating'] = $item['rating'] * $user['score'] * 0.1;
}
$results[] = $items:
}
but to no avail. What am I doing wrong and how do I get the desired result?
Upvotes: 0
Views: 112
Reputation: 146
By default in foreach the value is passed by value
. So even if you change the data inside of an array inside the loop it will not be reflected. So you have to use &
before $item
to pass the array data by reference
.
You can learn more about it here http://php.net/manual/en/control-structures.foreach.php
Upvotes: 1