Heim  >  Fragen und Antworten  >  Hauptteil

Warum wird mein Array zweimal statt einmal gemischt?

Ich habe einen Fragebogen zu http-Codes erstellt, hier ist ein Beispiel für 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'
                ],
            ];
    }

Dann ist mein Formulartyp:

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
        ]);
    }
}

Endlich mein 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');
    }
}

Auf der Indexseite unter der URL https://127.0.0.1:8001/ druckt mein erster Dump das Array in der richtigen Reihenfolge, die Dumps 2 und 3 werden in der falschen Reihenfolge gedruckt:

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"
  ]
]

Aber wenn ich das Formular abschicke, gibt dd meinen Array-Shuffle erneut aus:

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"
  ]
]

Ich verstehe nicht, warum das so gemacht wird. Wenn ich dd,提交表单后,我将使用不同的数组重定向到 https://127.0.0.1:8001/?question=1 ,如果我再次提交,我将重定向到 https://127.0.0.1 :8001/?question=2 entferne, wird dieses Mal dasselbe Array wie auf der vorherigen Seite verwendet und das Array ist nicht mehr zufällig.

Das bedeutet also, dass mein Array zweimal gemischt wird:

Aber ich möchte das Array nur einmal mischen, wenn ich die Localhost-Seite erreiche

Ich habe keine Ahnung, warum das so ist, wenn Sie irgendwelche Ideen haben, würde es Spaß machen

P粉818561682P粉818561682187 Tage vor238

Antworte allen(1)Ich werde antworten

  • P粉189606269

    P粉1896062692024-03-20 10:51:44

    当您提交表单时,您没有传递 question 参数。所以代码

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

    设置默认值$indiceQuestion = 0,再次陷入数组打乱的情况。

    您可以像这样转换条件

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

    或检查其他条件,例如 $session->get('questionsList') 中是否存在值

    Antwort
    0
  • StornierenAntwort