0

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.

6
  • in your first array, there is 2 index with name question... and your sorting end like question, question, question 2... Commented Mar 5, 2019 at 8:48
  • and the solution you asked for is sorting like question, question2 where is another key with name question is gone? what you want to do with it? Commented Mar 5, 2019 at 8:48
  • Can you please provide sample response for $questions = $this->getQRepository()->findAll();? Commented Mar 5, 2019 at 8:51
  • It returns all data from questions table and that is a data that I am trying to sort. @Olawale Commented Mar 5, 2019 at 9:04
  • If the data are from the db, then just do group by query Commented Mar 5, 2019 at 9:09

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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,

Comments

0

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',
    ),
  ),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.