2017-03-02 109 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

请阅读更新的问题。 –