在PHP implode中将数组与字符串变量合并

在PHP implode中将数组与字符串变量合并

问题描述:

implode(',', $a);

I want to attach the $q variable in front of the $a so like this

implode(',', $q.$a); 

But that doesn`t work. How can i put 2 variables in a implode function?

$a is an array with domain names like "com, org" and $q is the text (string) you type in before the domain names will appear.

I get the following error:

invalid argument passed in line..

Whole code:

$a = ['nl','net','com','co'];
$q = $_REQUEST["q"];

$domain = explode(".", $q);
$ext = @$domain[1] ?: ' ';


if (empty($ext)) {
    echo implode(',',$a);
} else if (in_array($ext, $a)) {
    echo $q;
} else {
    $r = [];
    foreach ($a as $x) {
        if (strstr($x, $ext)) {
            $r[] = $x;
        }
    }
    echo (count($r)) ? implode(',',$r) : implode(',',$a);
}
  implode(',',$ a); 
  code>  pre> \  n 
 

我想在 $ a code>前面附加 $ q code>变量,所以就像这样 p>

  implode(',',$ q。$ a);  
  code>  pre> 
 
 

但这不起作用。 如何在implode函数中放入2个变量? p>

$ a code>是一个域名如“com,org”和 $ q 是在域名出现之前键入的文本(字符串)。 p>

我收到以下错误: p>

行中传递的无效参数.. p> blockquote>

整个代码: p>

  $ a = ['nl','net','com','co']; 
 $ q =  $ _REQUEST [“q”]; 
 
 $ domain = explode(“。”,$ q); 
 $ ext = @ $ domain [1]?:''; 
 
 
if(空(  $ ext)){
 echo implode(',',$ a); 
} else if(in_array($ ext,$ a)){
 echo $ q; 
} else {
 $ r =  []; 
 foreach($ a as $ x){
 if(strstr($ x,$ ext)){
 $ r [] = $ x; 
} 
} 
 echo(count(count(  $ r))?  implode(',',$ r):implode(',',$ a); 
} 
  code>  pre> 
  div>

If $a is an array and $q is the prefix string you can achieve that with 2 steps:

Add the prefix with:

$a = array("com", "co");
$q = "robot.";
foreach ($a as &$value)
    $value = $q.$value;

Second, use the implode:

echo implode(',',$a);

output is:

robot.com,robot.co

Edited

I think this will be more suitable for you:

$a = array("com", "co", "org");
$q = "robot.c";
$arr =  explode(".", $q);

$output = array();
foreach ($a as &$value) {
    if (substr($value, 0, strlen($arr[1])) === $arr[1])
        $output[]= $arr[0] . "." . $value;
}
echo implode(',',$output);

In this code you take the domain prefix and search for all domain name that may be fit for the prefix.

Notice that is this example we have domain org but he does not show up because your prefix is c

You need to add your $q before implode function. You can add your $q into your $a array using array_map function.

$array = array('com', 'org', 'net');
$q = 'test';
$array = array_map(function($value) { 
                    $q= "test"; // you $q value goes here.
                    return $q.".".$value; 
         }, $array);

echo implode(',',$array);

Try This

$a = array("com", "co");
$q = "robot.c";
$temp = explode(".",$q);
foreach ($a as $value)
    echo $value = $temp[0].".".$value;