現在、私のメソッドをリファクタリングしています。 私はすでに長いforeachと状態を削除しましたが、今は素晴らしいマップ機能を持つために最後の仕上げで少し苦労しています。マップ機能のリファクタリングが改善されました
私の方法は次のようになります。ここで
/**
* @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;
}
、私は2つの質問があります:
を配列を代入良い方法はありますか?私はその後、
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, ];
しかし、のようなリターンに直接割り当てることにしようとしているとき、私は未定義のインデックスエラーが発生します。
- 要約された配列を返す最適な方法はありますか?私は同じクライアントのためにいくつかの時間のエントリがあるので、最後に、私は要約秒を欲しいです。それは私の例では機能しますが、私はそれを行う良い方法があると思います。私はマップ関数の外でそれを参照する必要がある$ arrayIndexを定義する必要があるので特に。これが最善の方法だとは思わないでください。任意のアドバイスや助けを
$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; } }
ありがとう:ここ
は、元のソースです!
元の「長いforeachとifの状態」のコピーはまだありますか? –
はい、私は私の元の投稿を編集します – mastercheef85