我尝试重构我的代码,但我的代码表现不佳。目标是获得具有 unique 的数组列表"answer_id",并获得一些“分数”、“投票”等。
在我现有的元素中,我首先检查 $most_voted 是否为 null,如果是,我分配第一个元素,然后我将在第二个元素中插入一个foreach新元素,或者我更新一个现有元素。但是从我的第二个开始foreach,我就过得很糟糕。关于这个逻辑有什么建议吗?
$answers = $history->toArray(); //here I have an array of arrays
$most_voted = [];
foreach ($answers as $key => $answer) {
if (!empty($most_voted) ) {
// in this if I create new arrays or I update existing ones
foreach ($most_voted as $k => $v) {
//If value already exists, increase Votes/Score/Percentage
if (intval($most_voted[$k]['answer_id']) === intval($answer['lkp_answer_id'])) {
$most_voted[$k]['Votes'] = $most_voted[$k]['Votes'] + 1;
$most_voted[$k]['Score'] = $most_voted[$k]['Score'] + $answer['score'];
$most_voted[$k]['Percentage'] = substr((($most_voted[$k]['Votes'] * 100) / $votes), 0, 5);
$most_voted[$k]['Weight'] = substr((($most_voted[$k]['Score'] * 100) / $total_scoring), 0, 5);
//Else add new array element
} else {
$name = LkpAnswer::where('id', '=', $answer['lkp_answer_id'])->pluck('name');
(isset($name[0]) && $name[0] !== null) ? $name = $name[0] : '';
if(! empty($answer['lkp_answer_id'])){
$most_voted[$key] = [
'answer_id' => $answer['lkp_answer_id'],
'Name' => $name,
'Votes' => 1,
'Score' => $answer['score'],
'Percentage' => substr(((1 * 100) / $votes), 0, 5),
'Weight' => substr((($answer['score'] * 100) / $total_scoring), 0, 5),
];
}
}
}
}
尚方宝剑之说