【问题标题】:how to extract data to array value如何将数据提取到数组值
【发布时间】:2018-03-26 02:08:41
【问题描述】:
$match = DiraChatLog::where('status','=','Match')
->selectRaw('DATE(created_at) as date, COUNT(1) as cnt') // created_at here is datetime format, only need the date portion using `DATE` function
->orderBy("date")
->groupBy("date")
->get() // return result set (collection) from query builder
->pluck('cnt') // only need the cnt column
->values() // array_values
->all(); // convert collection to array

使用上面的代码,我会在我的视图中得到如下输出:

但我必须稍微更改我的代码才能获得另一个日期值,以及何时使用我的代码进行此操作

$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
// $array[] = [];
foreach ($matchs as $key => $match) {
    $day = substr($match->date_access, 0, 10);
    if(isset($array[$day]))
    {
      $array[$day]++;
    } else 
    {
      $array[$day] = 1;
    }
    $match = $array;
}

现在我在我的视图中得到输出,例如:

现在我怎样才能将它们变成一个数组?例如,它应该是 ["2018-03-04", 3] 等等,具有以下日期和值。我该怎么做?我这样做的原因是,当我插入要在 highcharts 上查看的值时,第一种方式它可以工作,但第二种方式它不查看

【问题讨论】:

  • 使用toArray()json_decode() 将资源集合转换为PHP 数组。然后循环遍历数组并按照需要的格式处理字符串。

标签: php arrays laravel highcharts


【解决方案1】:

使用 Laravel 的收集方法transform 对收集结果进行转换。然后将集合转换为数组。

类似这样的:

$match = DiraChatLog::where('status','=','Match')
    ->selectRaw('DATE(created_at) as date, COUNT(1) as cnt') // created_at here is datetime format, only need the date portion using `DATE` function
    ->orderBy("date")
    ->groupBy("date")
    ->get(); // return result set (collection) from query builder

$match = $match->transform(function($item) {
    return [
        substr($item->date, 0, 10),
        $item->cnt,
    ];
})->toArray()

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2016-01-14
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多