-1

I have this JSON array:

[
  {
    "id": 101,
    "name": "White"
  },
  {
    "id": 102,
    "name": "Black"
  }
]

It was generated by my **actionIndex()** function and Yii2 Framework:

public function actionIndex()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    $colors = Colors::find()
        ->select([
            'id',
            'name'
        ])
        ->asArray()
        ->all();

    return $colors;
}

I need to add some text to the array. The result has to be like this:

{
  "error": false,
  "error_message": null,
  "data": [
    {
      "id": 101,
      "name": "White"
    },
    {
      "id": 102,
      "name": "Black"
    }
  ]
}

I tried to use array_push function but it doesn't work:

$father = [];
array_push($father, $colors);
3
  • 1
    You can just create a new array and specific error, error_message and then data which contains your array Commented Aug 8, 2018 at 16:21
  • 1
    Roby, please mark my answer as accepted in case it solve your issue. Thanks Commented Aug 8, 2018 at 16:33
  • 2
    Possible duplicate of PHP add an array inside an array Commented Aug 8, 2018 at 19:16

1 Answer 1

0

This could solve your issue:

public function actionIndex()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    $response = ['error'=>false, 'error_message'=>null];
    $response['data'] = Colors::find()
        ->select([
            'id',
            'name'
        ])
        ->asArray()
        ->all();


    return $response;
}

Since Output of this function is JSON response which is being converted from array we are retuning. So I have initialize the $response array with default values and then on 'data' index of the assign the array of colors. So it will give desire result as expected.

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

1 Comment

You should explain what you actually did to make this work. In it's current form it's largely a "code only answer" which is not really very beneficial overall (even if it helps OP immediately, it will not really help future visitors or anyone who actually wants to learn)

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.