Why is my array shuffled twice instead of once?
P粉818561682
P粉818561682 2024-03-19 23:11:47
0
1
284

I created a questionnaire about http codes, here is an example of 100 codes:

public static function list(): array
    {
        return
            [
                [
                    'http_message' => 'Continue',
                    'http_code' => '100'
                ],
                [
                    'http_message' => 'Switching Protocols',
                    'http_code' => '101'
                ],
                [
                    'http_message' => 'Processing',
                    'http_code' => '102'
                ],
                [
                    'http_message' => 'Early Hints',
                    'http_code' => '103'
                ],
            ];
    }

Then my form type:

class QuizControllerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('response', TextType::class, [
                'attr' => ['autofocus' => true]
            ])
            ->add('submit', SubmitType::class, array(
                'label' => 'Suivant'
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            // Configure your form options here
        ]);
    }
}

Finally my controller:

<?php

namespace App\Controller;

use App\Form\QuizControllerType;
use App\Service\HttpCodeService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class QuizController extends AbstractController
{
    #[Route('/', name: 'app_quiz')]
    public function index(Request $request): Response
    {
        $session = $request->getSession();

        $form = $this->createForm(QuizControllerType::class);

        $indiceQuestion = $request->query->get('question', 0);

        if (0 === $indiceQuestion) {
            $session->clear();
            $questionsList = InformationCodeService::list();
            dump(1,$questionsList);
            shuffle($questionsList);
            dump(2,$questionsList);
            $responses = array_column($questionsList, 'http_code');
            $session->set('questionsList', $questionsList);
            $session->set('responses', $responses);
            $session->set('responseFromUser', []);
        }

        $responseFromUser = $session->get('responseFromUser');

        $message = \count($session->get('questionsList')) > $indiceQuestion ? $session->get('questionsList')[$indiceQuestion]['http_message'] : '';

        $form->handleRequest($request);

        if ('' === $message) {
            dump('je passse');
            $results = [];

            $responses = $session->get('responses');
            $questionsList = $session->get('questionsList');

            for ($i = 0; $i < count($responseFromUser); $i  ) {
                if ($responseFromUser[$i] === $responses[$i]) {
                    $results[$i] = $responseFromUser[$i];
                }
            }

            $score = \count($results). ' / '. \count($questionsList);
            $session->set('score', $score);
            return $this->redirectToRoute('app_quiz_finish');
        }

        dump(3,$session->get('questionsList'));

        if ($form->isSubmitted() && $form->isValid()) {
            dd($session->get('questionsList'));
            $response = $form->getData()['response'];
            $responseFromUser[] = $response;
            $session->set('responseFromUser', $responseFromUser);
            $indiceQuestion  ;
            dd($indiceQuestion);

            return $this->redirectToRoute('app_quiz', ['question' => $indiceQuestion]);
        }

        return $this->render('quiz/index.html.twig', [
            'form' => $form->createView(),
            'message' => $message,
            'indice_question' => $indiceQuestion,
            'total_question' => \count($session->get('questionsList'))
        ]);
    }
    #[Route('/finish', name: 'app_quiz_finish')]
    public function finish(): Response
    {
        return $this->render('quiz/finish.html.twig');
    }
}

在 url https://127.0.0.1:8001/ 的索引页上,我的第一个转储按顺序打印数组,转储 2 和 3 打乱顺序打印:

array:4 [▼
  0 => array:2 [▼
    "http_message" => "Early Hints"
    "http_code" => "103"
  ]
  1 => array:2 [▼
    "http_message" => "Processing"
    "http_code" => "102"
  ]
  2 => array:2 [▼
    "http_message" => "Continue"
    "http_code" => "100"
  ]
  3 => array:2 [▼
    "http_message" => "Switching Protocols"
    "http_code" => "101"
  ]
]

But when I submit the form, dd prints my array shuffle again:

array:4 [▼
  0 => array:2 [▼
    "http_message" => "Processing"
    "http_code" => "102"
  ]
  1 => array:2 [▼
    "http_message" => "Switching Protocols"
    "http_code" => "101"
  ]
  2 => array:2 [▼
    "http_message" => "Continue"
    "http_code" => "100"
  ]
  3 => array:2 [▼
    "http_message" => "Early Hints"
    "http_code" => "103"
  ]
]

I don't understand why this is done. If I remove dd, after submitting the form, I will be redirected to https://127.0.0.1:8001/?question=1 with a different array, and if I submit again, I redirect to https://127.0.0.1:8001/?question=2 but this time with the same array as the previous page and the array is no longer random.

So this means my array is shuffled twice:

  • First when I get to the page
  • When submitting the first form for the second time

But I only want to shuffle the array once when reaching the localhost page

I have no idea why it does this, if you have any ideas it would be a pleasure

P粉818561682
P粉818561682

reply all(1)
P粉189606269

When you submitted the form, you did not pass the question parameter. So code

$indiceQuestion = $request->query->get('question', 0);

Set the default value$indiceQuestion = 0, and the array will be disrupted again.

You can convert the condition like this

if (0 === $indiceQuestion && !$form->isSubmitted())

Or check other conditions, such as whether the value exists in $session->get('questionsList')

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template