Reputation: 63
I have one array using i want to make my json response but i am not able do this:
print_r($exist_email);
Array
(
[user_id] => 3
)
I tried like this
$response_array['status']='Exist User';
$response_array['message']='Email already exists.';
$response_array['data']=$exist_email;
$this->response($this->json($response_array), 200);
public function response($data,$status=200){
$this->_code = ($status)?$status:200;
$this->set_headers();
echo $data;
exit;
}
protected function json($data){
if(is_array($data)){
return json_encode($data);
}
}
I am getting response
{
"status": "Exist User",
"message": "Email already exists.",
"data": {
"user_id": "3"
}
}
My expected output
{
"status": "Exist User",
"message": "Email already exists.",
"data": [
{
"user_id": "3"
}
]
}
Upvotes: 2
Views: 58
Reputation: 6223
Your expected output is array of array so you need to have $response_array['data']
to be an array.
Just replace this line
$response_array['data']=$exist_email;
with
$response_array['data'][]=$exist_email;
Upvotes: 0
Reputation: 4066
As per my comments you should used multidimensional array in this line $response_array['data']=$exist_email;
Above line you can replace with below lines
$response_array['data'][0]=$exist_email;
OR
$response_array['data'][]=$exist_email;
Here you can check your desired Output
Upvotes: 3
Reputation: 1633
You need to take array to get desired output.
You may try below code :
<?php
$response_array['status']='Exist User';
$response_array['message']='Email already exists.';
$response_array['data'][]= array('user_id' => 3);
echo json_encode($response_array, JSON_PRETTY_PRINT);
check : https://3v4l.org/o2QGX
Upvotes: 0
Reputation: 26844
If you are expecting an array, you can:
$response_array['data'] = array();
$response_array['data'][] = $exist_email;
$response_array['data'][] = $exist_email2; /* For the second, (optional) */
Upvotes: 1