如何在JSON响应中返回数组而不是对象?

I've one working REST API developed using Slim PHP framework.

It's working absolutely fine.

The only issue is when there is no error present i.e. an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.

Actually I want to return the array when error is present. How should I do this? Can someone please help me in this regard?

Thanks in advance.

When your $errors is not empty, pass it through json_encode and echo it. It will give you JSON object in return, then convert JSON object into JavaScript array. (see the following code.)

var o = {"0":"1","1":"2","2":"3","3":"4"}; // your response object here 

var arr = Object.keys(o).map(function(k) { return o[k] });

console.log(arr);