【问题标题】:Convert data rows to 1 object将数据行转换为 1 个对象
【发布时间】:2020-02-11 06:24:24
【问题描述】:

阅读 Laravel 6 行之类的

 {"filter_options":[
   {"id":5,"key":"category_id","value":"2","created_at":"2020-02-10 18:23:48"},
   {"id":4,"key":"only_with_images","value":"1","created_at":"2020-02-10 18:23:48"}
  ]
 } 

我需要转换 1 个对象中的数据,例如

{ 
   category_id : 2,
   only_with_images :"1"
}

我知道如何用一个共同的圆圈来实现,但是有一些集合映射方法吗?

谢谢!

【问题讨论】:

    标签: laravel collections


    【解决方案1】:

    我不确定您的数据是否是集合,但我们假设这是数据

    $array = ['filter_options' => [
        ['id' => 5, 'key' => 'category_id', 'value' => 2, 'created_at' => '2020-02-10 18:23:48'],
        ['id' => 4, 'key' => 'only_with_images', 'value' => 1, 'created_at' => '2020-02-10 18:23:48'],
       ]];
    

    你只需要这样做

        //after php 7.4
        return collect($array['filter_options'])->flatMap(fn ($item) => [$item['key'] => $item['value']]);
        //before php 7.4
        return collect($array['filter_options'])->flatMap(function ($item) {
            return [$item['key'] => $item['value']];
        });
    

    注意:显然这是访问属性的数组语法($item['key']),如果你的数据源来自 laravel eloquent,你可能不需要 collect() 辅助方法,你需要使用访问$item->key等属性的对象方式。

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 2020-09-09
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2020-06-17
      相关资源
      最近更新 更多