将Laravel查询转换为关键值?

时间:2016-03-10 08:17:50

标签: php mysql arrays laravel collections

我刚开始学习Laravel,我的查询结果如下:

[
  {
    servicename: "test",
    thing: "1"
  },
  {
    servicename: "test",
    thing: "2"
  },
  {
    servicename: "test",
    thing: "3"
  },
  {
    servicename: "test2",
    thing: "4"
  },
  {
    servicename: "test2",
    toothnum: "5"
  },
  {
    servicename: "test2",
    thing: "6"
  }
]

是否可以将其转换为:

  {
    services: {
      test:[
         "1",
         "2",
         "3"
       ]
      test2:[
         "4",
         "5",
         "6"
       ]
    }

  }

基本上我希望结果集能够在我的视图中循环,这样我就可以显示每个服务的“内容”。

1 个答案:

答案 0 :(得分:0)

你可以通过像这样循环你的数组来做到这一点:

$output_arr = array();
foreach($your_arr as $val)
{
 $output_arr[$val['servicename']][] = $val['thing'];
}

print_r($output_arr);