изменить значение элемента массива, Laravel - PullRequest
1 голос
/ 15 апреля 2020

Я хочу создать массив объектов, и если некоторые из них дублируются, я хочу увеличить некоторые поля, такие как (Голоса / Оценка / Процент), все хорошо .. в дампе (я получаю отредактированное значение, но на последний dd, массив не изменен. Там у меня есть все элементы.

В конце у меня есть 16 элементов массива (13 +3 с тем же lkp_answer_id), инсталяция из 13.

$history = AnswerHistory::where('question_id', '=', $id)->get();
$answers = $history->toArray();
$most_voted = [];
        foreach ($answers as $key => $answer) {
            if (!empty($most_voted)) {
                foreach ($most_voted as $best) {
                    //If value already exists, increase Votes/Score/Percentage
                    if ($best['answer_id'] == $answer['lkp_answer_id']) {
                        $best['Votes']++;
                        $best['Score'] = $best['Score'] + $answer['score'];
                        $best['Percentage'] = substr((($best['Votes'] * 100) / $query->votes), 0, 5);
                        $best['Weight'] = substr((($best['Score'] * 100) / $query->total_scoring), 0, 5);
                        dump($best);  //here the array element is changed (correct)
                    //Else add new array element
                    } else {
                        $most_voted[$key] = [
                            'answer_id' => $answer['lkp_answer_id'],
                            'Votes' => 1,
                            'Score' => $answer['score'],
                            'Percentage' => substr(((1 * 100) / $query->votes), 0, 5),
                            'Weight' => substr((($answer['score'] * 100) / $query->total_scoring), 0, 5),
                        ];
                    }
                }
            } else {
                //If $most_voted is null, insert first value
                $most_voted[$key] = [
                    'answer_id' => $answer['lkp_answer_id'],
                    'Votes' => 1,
                    'Score' => $answer['score'],
                    'Percentage' => substr(((1 * 100) / $query->votes), 0, 5),
                    'Weight' => substr((($answer['score'] * 100) / $query->total_scoring), 0, 5),

                ];
            }
        }

        dd($most_voted); //here I have a full list with, even duplicate ones

1 Ответ

1 голос
/ 15 апреля 2020

Измените свой код, как показано ниже, и попробуйте

$history = AnswerHistory::where('question_id', '=', $id)->get();
$answers = $history->toArray();
$most_voted = [];
        foreach ($answers as $key => $answer) {
            if (!empty($most_voted)) {
                foreach ($most_voted as $k => $v) {
                    //If value already exists, increase Votes/Score/Percentage
                    if ($most_voted[$k]['answer_id'] == $answer['lkp_answer_id']) {
                        $most_voted[$k]['Votes']++;
                        $most_voted[$k]['Score'] = $most_voted[$k]['Score'] + $answer['score'];
                        $most_voted[$k]['Percentage'] = substr((($most_voted[$k]['Votes'] * 100) / $query->votes), 0, 5);
                        $most_voted[$k]['Weight'] = substr((($most_voted[$k]['Score'] * 100) / $query->total_scoring), 0, 5);
                        dump($most_voted[$k]);  //here the array element is changed (correct)
                    //Else add new array element
                    } else {
                        $most_voted[$key] = [
                            'answer_id' => $answer['lkp_answer_id'],
                            'Votes' => 1,
                            'Score' => $answer['score'],
                            'Percentage' => substr(((1 * 100) / $query->votes), 0, 5),
                            'Weight' => substr((($answer['score'] * 100) / $query->total_scoring), 0, 5),
                        ];
                    }
                }
            } else {
                //If $most_voted is null, insert first value
                $most_voted[$key] = [
                    'answer_id' => $answer['lkp_answer_id'],
                    'Votes' => 1,
                    'Score' => $answer['score'],
                    'Percentage' => substr(((1 * 100) / $query->votes), 0, 5),
                    'Weight' => substr((($answer['score'] * 100) / $query->total_scoring), 0, 5),

                ];
            }
dd($most_voted); //here I have a full list with, even duplicate ones
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...