Reputation: 2228
I have to combine two array into single inside Json encode. my code is,
$email = $_GET["email"];
$password = $_GET["password"];
$query = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length == 1)
{
$var[] = array('status'=>"success");
while($obj = mysqli_fetch_object($result))
{
$var[] = $obj;
}
echo '{"login":'.json_encode($var).'}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"login":['.json_encode($arr).']}';
}
Now the result is,
{"login":[{"status":"success"},{"login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"[email protected]","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}
And the require output is,
{"login":[{"status":"success","login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"[email protected]","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}
How to combine array. I have tried a lot.
Upvotes: 1
Views: 70
Reputation: 20469
You can use array_merge
to get the exact output you request:
$email = $_GET["email"];
$password = $_GET["password"];
$query = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
$response = [];
if($length == 1)
{
$response['login'] = arry(array_merge(array('status'=>"success"), mysqli_fetch_assoc($result)));
}
else
{
$response['login'] = array(array('status'=>"notfound"));
}
header('Content-Type: application/json');
echo json_encode($response);
Note that it seems unnecessary to have login
property be an array when there is only one result, so it would make sense to remove the outer array wrap:
if($length == 1)
{
$response['login'] = array_merge(array('status'=>"success"), mysqli_fetch_assoc($result));
}
else
{
$response['login'] = array('status'=>"notfound");
}
Upvotes: 1
Reputation: 24276
Change
$var[] = array('status'=>"success");
while($obj = mysqli_fetch_object($result))
{
$var[] = $obj;
}
to
$var['status'] = "success";
// use the assoc fetch here.. to avoid casting to array
while($arr = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $arr);
}
Upvotes: 4
Reputation: 273
It's a wild guess, but try this.
$result = array(
'login' => $var
);
echo json_encode($result);
Upvotes: 0