develops
develops

Reputation: 319

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.

Upvotes: 0

Views: 95

Answers (3)

mickmackusa
mickmackusa

Reputation: 47894

In your loop, create a group reference for each unique title value encountered then only push references into the result array. As for the answers, they will always be pushed into the second element of the group reference. Demo

$mappedQuestions = [];
foreach ($questions as $question) {
    $title = $question->getTitle();
    if (!isset($ref[$title])) {
        $ref[$title] = [$title];
        $mappedQuestions[] = &$ref[$title];
    }
    $ref[$title][1][] = $question->getAnswer();
}
var_export($mappedQuestions);

Output:

array (
  0 => 
  array (
    0 => 'Question',
    1 => 
    array (
      0 => 'Answer',
      1 => 'Answer2',
    ),
  ),
  1 => 
  array (
    0 => 'Question2',
    1 => 
    array (
      0 => 'Answer3',
    ),
  ),
)

Upvotes: 0

Afif Zafri
Afif Zafri

Reputation: 625

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.

Upvotes: 1

HarisH Sharma
HarisH Sharma

Reputation: 1257

you need to iterate 2 loops to achieve it, I took your JSON in $json variable and then proceed as,

$json = '{
    "success": true,
    "data": [
        [
            "Question",
            [
                "Answer"
            ]
        ],
        [
            "Question",
            [
                "Answer 2"
            ]
        ],
        [
            "Question 2",
            [
                "Answer 3"
            ]
        ]
    ],
    "message": null
    }';

$arr = (array) json_decode($json, true);

foreach($arr['data'] AS $a){
    $newArr[ $a[ 0 ] ][] = array( $a[ 1 ][ 0 ] );
}

foreach($newArr AS $key => $a){
    $newArr2[] = array_merge(array($key), array_values($a));
}

$finalArr = array('success' => $arr['success'], 'data' => $newArr2, 'message' => $arr['message']);

print_r($finalArr); // this is final o/p which you want,

Note: this is may be not correct answer, but by this now you have an idea how to do,

Upvotes: 0

Related Questions