[英]Looping through multiple php arrays to change value
I have an array $users
as such: 我有这样的数组
$users
:
[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
: 然后,对于每个用户,我检索项目并将它们存储到数组
$results
:
foreach ($users as $user) {
$items = getItems($user['userid']);
$results[] = $items:
}
The $results
array ends up looking like this: $results
数组最终看起来像这样:
[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.
因此,对于每个项目,评分将乘以用户得分* 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?
我做错了什么,如何得到理想的结果?
By default in foreach the value is passed by value
. 默认情况下,在foreach中,值是
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
. 因此,您必须在
$item
之前使用&
来通过reference
传递数组数据。
You can learn more about it here http://php.net/manual/en/control-structures.foreach.php 您可以在此处了解更多信息http://php.net/manual/en/control-structures.foreach.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.