phparrayssorting

PHP - sorting arrays in group


I have trouble sorting my array result in a different way. I have written an API call that returns specified results but not in the right way.

So it gives me:

{
"success": true,
"data": [
    [
        "Question",
        [
            "Answer"
        ]
    ],
    [
        "Question",
        [
            "Answer 2"
        ]
    ],
    [
        "Question 2",
        [
            "Answer 3"
        ]
    ]
],
"message": null

}

And I want to return a group of answers for that question like:

{
"success": true,
"data": [
    [
        "Question",
        [
            "Answer"
        ],
        [
            "Answer 2"
        ]
    ],
    [
        "Question 2",
        [
            "Answer 3"
        ]
    ]
],
"message": null
}

And my code looks like:

$questions = $this->getQRepository()->findAll();

$mappedQuestions = [];

foreach ($questions as $question){

    $title = $question->getTitle();

    $mappedQuestions[] = [
        $title,
        [
            $question->getAnswer()
        ]
    ];
}

return $mappedQuestions;

It gives me the result where it groups every question with answer by id but I need to group all answers by question. The result returns correctly but sorting is wrong.


Solution

  • This might work, but I'm not sure if this is what you are looking for. So first, modified your current looping and $mappedQuestions array structure like this:

    $mappedQuestions = [];
    
    foreach ($questions as $question){
    
        $mappedQuestions[] = array(
                                   'title' => $question->getTitle(), 
                                   'answer' => $question->getAnswer()
                              );
    }
    

    After that, iterate the array one more time to create a new array that will group together the elements based on the array key, which in this case is "title".

    $sorted = array();
    foreach ($mappedQuestions as $element) {
        $sorted[$element['title']][] = $element['answer'];
    }
    
    return $sorted;
    

    The final output of $sorted is:

    {
       "Question":[
          "Answer",
          "Answer 2"
       ],
       "Question 2":[
          "Answer 3"
       ]
    

    The sort looping code is actually from this question.

    I hope this help.