Remove dynamic keys from array

I have mysqli query that I fetch and the code below turns results into array, but I get unwanted dynamic keys 1 ,2, 3 etc. my question is it possible to remove them or do it somehow differently?

if($num > 0) {
    $quest_arr['error'] = 'false';
    $quest_arr['message'] = 'Success';
    $quest_arr['data'] = array();

    $questions = [];
    foreach ($result as $r) {

          if (!isset($questions[$r['QuestionId']])) {
              $questions[$r['QuestionId']] = [ 'QuestionId' => $r['QuestionId'],
                                           'question'   => $r['QuestionName'],
                                           'answers'=> []
                                         ];
          }
          $questions[$r['QuestionId']]['answers'][] = $r['AnswerID'];

    }
    array_push($quest_arr['data'], $questions);


    echo json_encode($quest_arr, JSON_NUMERIC_CHECK);

  } else {
    echo json_encode(
      array('error' => 'true','message' => 'Error')

    );
  }

Creates this array

{
    "error": "false",
    "message": "Success",
    "data": [
        {
            "1": {
                "QuestionId": 1,
                "question": "Question 1",
                "answers": [
                    1,
                    2,
                    3
                ]
            },
            "2": {
                "QuestionId": 2,
                "question": "Question 2",
                "answers": [
                    null
                ]
            },
            "3": {
                "QuestionId": 3,
                "question": "Question 3",
                "answers": [
                    null
                ]
            },

        }
    ]
}

Is it possible to remove the dynamic keys "1", "2" ,"3" ?

I would love to have json like this

{
    "error": "false",
    "message": "Success",
    "data": [
        {
          "QuestionId": 1,
          "question": "Question 1",
          "answers": [
              1,
              2,
              3
          ]
        },
        {
          "QuestionId": 2,
          "question": "Question 2",
          "answers": [
              null
          ]
        },
        {
          "QuestionId": 3,
          "question": "Question 3",
          "answers": [
              null
          ]
        },

    ]
}

>Solution :

Not tested, but maybe this can work:

// instead of
// array_push($quest_arr['data'], $questions);
$questions = array_values($questions);
$quest_arr['data'] = $questions;

Leave a Reply