如何从REST API请求中获取数组值作为返回值?

时间:2019-03-15 14:15:59

标签: php

这个问题已经被提出,但是我需要一个适用于我的问题的解决方案。我能够通过php REST api发送值,但只返回了一个值。

我希望能够从curl请求中获取所有数组值。

下面是我的代码:

if(isset($_POST['btn-login']))
{

    $licence = $_POST['licence'];


        $ch = curl_init('http://totallightschools.com/apis/User/login.php?licence='.$licence);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        $data   = json_decode($response,true);
        if($data['status'] == true)
        {
        $_SESSION['licence'] = $data['licence'];
        echo $_SESSION['period'] = $data['period'];
        echo $_SESSION['user'] = $data['user'];
        echo $pin = $_SESSION['licence'];
            //echo "yes";
            //header("Location: setup.php?License=".$pin .'&period='.$_SESSION['period'].'&user='.$_SESSION['user']);
        }else
        {
            echo $data['message'];
        }


}

还有我的api网址

if($stmt->rowCount() > 0){
    // get retrieved row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    // create array
    $user_arr=array(
        "status" => true,
        "message" => "Successfully Validated!",
        "id" => $row['id'],
        "licence" => $row['licence'],
        "period" => $row['period'],
        "user" => $row['users']
    );
}
else{
    $user_arr=array(
        "status" => false,
        "message" => "Invalid Licence Key Entered. Please contact the software company.",
    );
}
// make it json format
print_r(json_encode($user_arr));

1 个答案:

答案 0 :(得分:0)

您需要在api代码中进行更改,并需要返回一个多维数组。当前,它仅在覆盖$user_arr时返回最后一个值。检查以下代码:

if($stmt->rowCount() > 0){
    // get retrieved row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    // create multidimensioanl array
    $user_arr[] = array(
        "status" => true,
        "message" => "Successfully Validated!",
        "id" => $row['id'],
        "licence" => $row['licence'],
        "period" => $row['period'],
        "user" => $row['users']
    );
}
else{
    $user_arr=array(
        "status" => false,
        "message" => "Invalid Licence Key Entered. Please contact the software company.",
    );
}
// make it json format
print_r(json_encode($user_arr));

希望它对您有帮助。