亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 PHP 中將標準類對象轉換為整型

如何在 PHP 中將標準類對象轉換為整型

PHP
阿波羅的戰車 2022-09-17 22:37:12
我想用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有多大
查看完整描述

2 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

您最好更改查詢,以便僅獲取要查找的用戶的值。

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


查看完整回答
反對 回復 2022-09-17
?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

如果值為“假”、“空”或“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 fails

if($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()...


我希望這能解決你的問題,讓我知道它是如何進行的。


查看完整回答
反對 回復 2022-09-17
  • 2 回答
  • 0 關注
  • 131 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號