将两个数组合并为单个内部json_encode

时间:2015-12-16 11:39:03

标签: php arrays

我必须将两个数组合并到单个内部Json编码中。我的代码是,

    $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).']}';
    }

现在的结果是,

{"login":[{"status":"success"},{"login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"example@gmail.com","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}

需求输出是,

{"login":[{"status":"success","login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"example@gmail.com","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]}

如何组合数组。我已经尝试了很多。

3 个答案:

答案 0 :(得分:4)

更改

$var[] = array('status'=>"success");
while($obj = mysqli_fetch_object($result)) 
{
    $var[] = $obj;
}

$var['status'] = "success";
// use the assoc fetch here.. to avoid casting to array
while($arr = mysqli_fetch_assoc($result)) 
{
    $var = array_merge($var, $arr);
}

答案 1 :(得分:1)

您可以使用array_merge获取您要求的确切输出:

$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);

请注意,当只有一个结果时,似乎没有必要将login属性作为数组,因此删除外部数组换行是有意义的:

if($length == 1)
{
    $response['login'] = array_merge(array('status'=>"success"), mysqli_fetch_assoc($result));
}
else
{
    $response['login'] = array('status'=>"notfound");
}

答案 2 :(得分:0)

这是一个疯狂的猜测,但试试这个。

$result = array(
    'login' => $var
);

echo json_encode($result);