我有一个db查询,它返回一个$result
变量的值,如下所示:
Collection {#710 ▼
#items: array:16 [▼
0 => {#717 ▼
+"utest_step_id": 18
+"value": "1"
+"count": 26
}
1 => {#716 ▼
+"utest_step_id": 18
+"value": "2"
+"count": 23
}
2 => {#709 ▶}
3 => {#711 ▶}
4 => {#713 ▶}
5 => {#714 ▶}
6 => {#715 ▶}
7 => {#718 ▶}
8 => {#719 ▶}
9 => {#720 ▶}
10 => {#721 ▶}
11 => {#722 ▶}
12 => {#723 ▶}
13 => {#724 ▶}
14 => {#725 ▶}
15 => {#726 ▶}
]
}
我有一个名为$steps
的数组,我需要将其与这样的数据结合起来:
[▼
0 => {#676 ▼
+"id": 18
+"step": 1
+"type": "select many image"
+"featured": false
+"data": {#664 ▼
+"description": "Ut quaerat ut sed molestiae."
+"randomize": 0
+"options": array:4 [▼
0 => {#671 ▼
+"position": 1
+"image_url": "http://lorempixel.com/455/255/?67678"
+"caption": "Prof."
+"image_source": "http://lorempixel.com/455/255/?67678"
}
1 => {#668 ▼
+"position": 2
+"image_url": "http://lorempixel.com/455/255/?23876"
+"caption": "Ms."
+"image_source": "http://lorempixel.com/455/255/?23876"
}
2 => {#670 ▼
+"position": 3
+"image_url": "http://lorempixel.com/455/255/?45833"
+"caption": "Prof."
+"image_source": "http://lorempixel.com/455/255/?45833"
}
3 => {#677 ▼
+"position": 4
+"image_url": "http://lorempixel.com/455/255/?83800"
+"caption": "Dr."
+"image_source": "http://lorempixel.com/455/255/?83800"
}
]
}
}
1 => {#690 ▶}
2 => {#697 ▶}
3 => {#704 ▶}
4 => {#706 ▶}
]
我正在尝试将count
中$results
的值插入$steps->data->options
数组中。
这是我的代码:
foreach ($results as $result) {
$comparison_field = 'position';
for ($i=0; $i < sizeof($steps); $i++) {
if ($result->utest_step_id == $steps[$i]->id) {
foreach ($steps[$i]->data->options as $option) {
$option->count = 0;
$option->count = $result->count;
}
}
}
}
问题是我最终会得到$result->utest_step_id
中每个count
项中最后$option
的计数。
我哪里错了?
答案 0 :(得分:0)
对于$steps
中的每个条目,您有一个for循环遍历$results
中的所有元素。这导致$steps
中的所有内容都被覆盖$results
中的每个元素。如果这些数组应该排成一行,请从$id
循环中获取$results
:
foreach ($results AS $id=>$result)
并在for循环中使用它代替$i
。