【问题标题】:How to combine the output from an object and an array?如何组合对象和数组的输出?
【发布时间】:2018-08-01 07:16:45
【问题描述】:

我有一个 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 ▶}
]

我正在尝试将来自 $results 中的 count 的值插入到 $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;

            }
        }
    }
}

问题是我最终得到了$option 中每个count 项目中最后一个$result-&gt;utest_step_id 的计数。

我哪里错了?

【问题讨论】:

    标签: php arrays object foreach


    【解决方案1】:

    对于$results 中的每个条目,您有一个循环遍历$steps 中的所有元素。这导致$steps 中的所有内容被$results 中的每个元素覆盖。如果这些数组应该对齐,请从$results 循环中获取$id

    foreach ($results AS $id=>$result)
    

    并在 for 循环中使用它而不是 $i

    【讨论】:

      猜你喜欢
      • 2012-07-25
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多