【问题标题】:How to use array values outside foreach loop?如何在 foreach 循环之外使用数组值?
【发布时间】:2017-07-22 00:50:06
【问题描述】:

如何在 Laravel 5.4 的 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”后缀, 然后用逗号分隔它们,并将它们作为变量用于查询 url。
P.S:我正在使用 guzzlehttp 向 API 发送请求。所以应该放在:

'DomainList' => $domainlist

我该怎么做?

【问题讨论】:

  • $string 在您的foreach loop 中将在每个循环中替换其值。因此,您需要使用 .= 进行连接。在等于之前记住(点)。
  • 是返回任何错误信息

标签: php arrays laravel laravel-5 foreach


【解决方案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 集合有一个用于内爆数组的命令,因此除非您计划对数据进行其他操作,否则无需使用 pluck 和循环遍历数组。

编辑:根据更新的问题,听起来您正在寻找这样的东西:

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
}

【讨论】:

    【解决方案2】:

    当您使用 pluck() 方法时,它会返回给定名称的数组 所以你不需要使用 foreach 循环

    随便用

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

    【讨论】:

      【解决方案3】:

      你试试看

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        • 2017-08-03
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多