2017-03-02 41 views
1

如何在Laravel 5.4的foreach循環外使用數組值?
下面是代碼:
如何在foreach循環之外使用數組值?

public function index(Request $request) 
    { 
     $name = $request->input('keyword'); 
     $category = $request->input('category'); 
     $catkeywords = array(DB::table('keywords')->pluck($category)); 
     foreach ($catkeywords as $catkeyword) { 
      $string = implode(',',$catkeyword); 
     } 
     echo $string; 
    } 

我不知道爲什麼它不工作!

我只是想從數據庫中返回的關鍵字組合他們提供一些文字,並使用一段API查詢

換句話說,我想要在循環之外的關鍵字列表

對於使用在這樣一個API查詢:

http://api-url/query?id=domain1.com,domain2.com,domain3.com 

$catkeywords返回關鍵字JSON格式名單。

現在我想將這些關鍵詞與用戶輸入的值添加一個「.COM」後綴, 然後將它們分開使用逗號,並利用它們對查詢網址作爲變量。
P.S:我正在使用guzzlehttp向API發送請求。因此,它應放在:

'DomainList' => $domainlist

我怎麼能這樣做?

+0

'$ string'你'的foreach loop'內將更換其第v在每個循環中都有。所以,你需要使用'。='連接。在等於之前記住(點)。 – vijayrana

+0

是否返回任何錯誤信息 – ashanrupasinghe

回答

1

如果您使用laravel,你應該考慮其藏品優勢:

https://laravel.com/docs/5.4/collections#method-implode

public function index(Request $request) 
{ 
    $name = $request->input('keyword'); 
    $category = $request->input('category'); 
    $catkeywords = DB::table('keywords')->implode($category, ','); 
    echo $catkeywords; 
} 

Laravel收藏有爆命令該數組,因此除非您計劃對數據執行其他操作,否則不需要使用採集和循環訪問數組。

編輯:基於更新的問題,這聽起來像你正在尋找的東西是這樣的:

public function index(Request $request) 
{ 
    $name = $request->input('keyword'); 
    $category = $request->input('category'); 
    $catkeywords = DB::table('keywords')->pluck($category); //You don't need to wrap this in an array() 
    $keywords = []; //Create a holding array 
    foreach ($catkeywords as $catkeyword) { 
     $keywords[] = $catkeyword . '.com'; //Push the value to the array 
    } 
    echo implode(',', $keywords); //Then implode the edited values at the end 
} 
+0

請閱讀更新的問題。 –

+0

謝謝,它工作(有一些修改)。 –

0

你嘗試做

public function index(Request $request) 
    { 
     $name = $request->input('keyword'); 
     $string = ''; 
     $category = $request->input('category'); 
     $catkeywords = array(DB::table('keywords')->pluck($category)); 
     foreach ($catkeywords as $catkeyword) { 
      $string .= implode(',',$catkeyword); 
     } 
     echo $string; 
    } 
+0

請閱讀更新後的問題。 –

0

當您使用動物內臟()方法,然後將它返回給定的名稱 所以你不要的數組都需要使用foreach循環

只使用

$catkeywords = array(DB::table('keywords')->pluck($category)); 
echo implode(',',$catkeyword); 
+0

請閱讀更新的問題。 –