Reputation: 313
How can I use an array values outside a foreach loop in Laravel 5.4?
Here is the code :
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;
}
I don't know why it doesn't work !
I just want the returned keywords from database to combine them with some text and to use for some API queries.
In other words, I want the list of keywords outside of the loop.
For using in an API query like this :
http://api-url/query?id=domain1.com,domain2.com,domain3.com
$catkeywords
returns a json formatted list of keywords.
Now I want to combine these keywords with a user-inputted value and add a ".com" suffix,
then separate them using commas and use them on query url as a variable.
P.S : I'm using guzzlehttp
for sending requests to the API. So it should be placed on :
'DomainList' => $domainlist
How can I do that ?
Upvotes: 1
Views: 3189
Reputation: 9
You try do that
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;
}
Upvotes: 0
Reputation: 2179
If you're using laravel, you should consider taking advantages of their collections:
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 collections have a command for imploding the array, so there's no need to use pluck and loop through the array unless you plan on doing other operations on the data too.
EDIT: Based on updated question, it sounds like you're looking for something like this:
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
}
Upvotes: 1
Reputation: 57
when you use pluck() method then it return array of given name so you dont have need to use foreach loop
just use
$catkeywords = array(DB::table('keywords')->pluck($category));
echo implode(',',$catkeyword);
Upvotes: 0