0

我目前正在重构我的方法。我已经消除了长 foreach 和 if 状态,但现在我在最后完成时有点挣扎以拥有一个不错的地图功能。

我的方法看起来像。

/**
 * @param \Illuminate\Support\Collection
 * @return array
 */
public static function convertTimesToChartData($times) {
    $clientTotal = '0';
    $arrayIndex = 0;
    $chartData = collect($times)->filter(function($item) {
        return !is_null($item->end_time);
    })->map(function($item) use(&$clientTotal, &$arrayIndex){
        $clients[$arrayIndex]['id'] = $item->client_id;
        $clients[$arrayIndex]['project_id'] = $item->project_id;
        $clients[$arrayIndex]['label'] = $item->company;
        $clients[$arrayIndex]['sec'] = $item->end_time->timestamp - $item->start_time->timestamp;
        $clientTotal += $item->end_time->timestamp - $item->start_time->timestamp;
        $arrayIndex++;
        return $clients;
    })->flatMap(function($item) { return $item; });


    return $chartData;
}

在这里,我有两个问题:

  1. 有没有更好的方法分配数组?当我尝试直接在返回中分配时

            return [
            [$arrayIndex]['id'] => $item->client_id,
            [$arrayIndex]['project_id'] => $item->project_id,
            [$arrayIndex]['label'] => $item->company,
            [$arrayIndex]['sec'] => $item->end_time->timestamp - $item->start_time->timestamp,
        ];
    

但后来我得到一个未定义的索引错误。

  1. 返回汇总数组的最佳方法是什么?因为我对同一个客户有几个时间条目,所以最后,我只想要汇总的秒数。它适用于我的示例,但我认为有更好的方法可以做到这一点。特别是因为我需要定义一个 $arrayIndex ,我需要在 map 函数之外声明并引用它。不要认为这是最好的方法。

这是原始来源:

    $projects = array();
    $projectTotal = '0';
    foreach($taskTimes as $time){
        if(!is_null($time->end_time))
        {
            if (isset($projects[$time->project_id]))
            {
                $projects[$time->project_id]['sec'] += $time->end_time->timestamp - $time->start_time->timestamp;
            } else
            {
                $projects[$time->project_id]['id'] = $time->client_id;
                $projects[$time->project_id]['label'] = $time->company;
                $projects[$time->project_id]['sec'] = $time->end_time->timestamp - $time->start_time->timestamp;
            }
            $projectTotal += $time->end_time->timestamp - $time->start_time->timestamp;
        }
    }

感谢您的任何建议和帮助!

4

1 回答 1

1

为了获得与原始 foreach 循环相同的结果,您可以这样做:

$projects = collect($taskTimes)
    ->filter(function ($time) {
        return !is_null($time->end_time);
    })
    ->groupBy('project_id')
    ->map(function ($group) {
        $group = collect($group);

        return [
            'id'         => $group->first()->client_id,
            'project_id' => $group->first()->project_id,
            'label'      => $group->first()->company,
            'sec'        => $group->sum(function ($item) {
                return $item->end_time->timestamp - $item->start_time->timestamp;
            }),
        ];
    });

$projectsTotal = $projects->sum('sec');

我已将它添加project_id到结果数组中,因为它包含在您的convertTimesToChartData()方法示例中

希望这可以帮助!

于 2017-03-12T15:25:20.843 回答