簡體   English   中英

從for循環中獲取值

[英]get the value from for loop

我想在php中獲取for循環值,我有一些名稱,我想在每個名稱后添加'/'並在循環外打印該值,我想從for循環中獲取$ approver_name

foreach($co_practice as $co_practice_approver){
    // global $approver_name;
    if ($j >= 1) {
        $approver = users::where('id','=',$co_practice_approver)->first()->firstname;
        $approver_name = $approver_name . ' / ' . $approver;    
    } else {
        $approver_name = users::where('id','=',$co_practice_approver)->first()->firstname;
    }
}

 Hello {{$approver_name}}

現在我得到沒有approver_name的輸出'hello'如何打印我在for循環中獲取的approver_name

為什么不立即獲取approverfirstname 循環獲取數據將導致數據庫中的多個查詢。 相反,您可以使用whereIn()

YourController.php

public function yourMethod {
    // your other logic here...

    // this will query to get all users matching ids in $co_practice array
    // and pluck() will get the array of user's firstname 
    $firstNames = UserModel::whereIn('id', $co_practice)->pluck('firstname');

    // this will concatenate firstnames separated by '/'
    $approver_name = implode(' / ', $firstNames->all());

    // this will pass the $approver_name variable to view
    return view('your_blade_file', compact('approver_name'));
}

your_blade_file.blade.php

//now you can print the $approver_name
Hello {{ $approver_name }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM