【问题标题】:Format multi dimensional array using Laravel collections使用 Laravel 集合格式化多维数组
【发布时间】:2017-03-23 01:00:50
【问题描述】:

我有一个这样的数组,它是数据库查询 (Google BigQuery) 的结果:

Array
(
    [0] => Array
        (
            [points] => 95
            [user] => 434
            [type] => 20
            [identifier] => tv
            [date] => 2016-11-01
        )

    [1] => Array
        (
            [points] => 349
            [id] => 2989631
            [type] => 20
            [identifier] => app
            [date] => 2016-11-01
        )
) 

另一个用于标识符:

Array
(
    [tv] => 1
    [app] => 2
)

我需要做的是转换数组,因为标识符键具有标识符数组中的对应值。所以它看起来像:

Array
(
    [0] => Array
        (
            [points] => 95
            [user] => 434
            [type] => 20
            [identifier] => 1
            [date] => 2016-11-01
        )

    [1] => Array
        (
            [points] => 349
            [id] => 2989631
            [type] => 20
            [identifier] => 2
            [date] => 2016-11-01
        )
) 

如何使用 Laravel 集合做到这一点?

我一直在尝试使用变换函数,但没有想到从多维数组中返回特定列。

【问题讨论】:

    标签: php arrays laravel collections laravel-collection


    【解决方案1】:

    你可以使用array_map():

    $identifiers = [
        'tv' => 1,
        'app' => 2
    ];
    
    $result = array_map(function($item) use ($identifiers) {
        $item['identifier'] = $identifiers[$item['identifier']];
        return $item;
    }, $itemsArray);
    

    【讨论】:

      【解决方案2】:

      这里最好的解决方案可能是使用acessor

      public function getIdentifier($value)
      {
          return $identifiersArray[$value];
      }
      

      如果你这样做,你将不需要重建你的收藏。

      【讨论】:

      • 一件事是我使用 Google Bigquery 作为数据库,因此使用他们的 API 来执行查询。他们基本上是在返回一个数组。
      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2020-03-09
      • 2021-10-28
      • 2017-04-06
      • 2019-07-05
      • 2021-12-02
      相关资源
      最近更新 更多