猿问

如何在 PHP 中将标准类对象转换为整型

我想用user_id搜索我的数据库,并得到金额值(int类型)


$user = (int)(request('user'));

    $money = (int)(request('money'));

    $data = (DB::select("select amount from user_check where user_id = '$user'"));

    $array = json_decode(json_encode($data), True);

    foreach ($data as $value) 

    {

        $array[] = $value->amount;

    } 

    if($array[0]>$money)

    {

        return response(['user ok'=>$array[0],'money'=>$money]);

    }

    else

    {

        //return response(['user'=>$user,'Not enough money'=>$data]);

        return response('user not ok');

    }

但它不起作用,它总是进入如果不知道$money有多大


阿波罗的战车
浏览 100回答 2
2回答

MYYA

您最好更改查询,以便仅获取要查找的用户的值。$amount = DB::table('user_check')->where('user_id', $user)->pluck('amount');或者如果金额是数组而不是单个值(取决于版本)$amount = DB::table('user_check')->where('user_id', $user)->value('amount');或$user = DB::table('user_check')->where('user_id', $user)->first(); $amount = $user ? $user->amount : 0;

精慕HU

如果值为“假”、“空”或“0”,则 (int) 将返回 0。我敢打赌,你不希望有这个查询来搜索ID为0的用户,以防请求输入未设置或格式不正确。让我们清理该代码:$userId = request()->get('user');$money = (int) request()->get('money'); # (int) here will be 0 if the request('money') is not sent with the request# so it makes sense to have it here.$userCheck = DB::table('user_check')->select('amount')            ->where('user_id', $userId)            ->first();# ->first(); if you want to return a single row item# ->get(); if you want to return multiple items, this one will return a collection (array) # and you need to treat that accordingly using foreach, or any array function为什么需要?$array = json_decode(json_encode($data), True);if($userCheck->amount > $money){    return response(['user ok'=> $userCheck,'money'=>$money]);}else{    return response('user not ok');}现在我假设你正在使用(int)来获取已发送数据的整数值,那里没有实际需要,并且在验证的情况下,你需要单独验证它,如下所示:如果它在控制器中$this->validate($request,[    'user'=>'required|exists:user_check,id',    'money'=>'integer']);如果要在其他地方进行验证,您可以:$validator = Validator::make($request->all(), [    'user'=>'required|exists:user_check,id',    'money'=>'integer']);# Check if it failsif($validator->fails()){   # Validator fails, stop and return the errors instead   return response()->with($validator->getMessageBag());}# This will validate the request and make sure that it has 'user'# And that 'user' exists in the `user_check` table with that ID# and that 'money' is an integer如果您愿意验证,则可以将该代码放在DB::table()...我希望这能解决你的问题,让我知道它是如何进行的。
随时随地看视频慕课网APP
我要回答