PHP:foreach循环将数组的值赋给连接的字符串和变量

时间:2018-05-18 17:01:37

标签: php arrays function foreach

我想将数组的值赋给具有变量的字符串:

    $my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {
foreach ($my_array_values as $my_array_value) {
$string_query = $string;
 echo $string_query . "<br>";
}
}

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '" . $my_array_value . "'";
my_function ($my_array_values, $string_variable);

如果我回应它,​​结果就是这个(不取变量的数组值):

    SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''

结果应该是这样的:

    SELECT login FROM table WHERE login = 'apple'
SELECT login FROM table WHERE login = 'orange'
SELECT login FROM table WHERE login = 'cellular'
SELECT login FROM table WHERE login = 'box'

我怎么能这样做? 亲切的问候

3 个答案:

答案 0 :(得分:1)

What is it you are trying to achieve? The MySQL IN function looks for values "IN" a subset or other pool of info.

$query= "SELECT login FROM table WHERE login IN ({implode(',', $my_array_values)})";

Would this be easier than looping over and over?

答案 1 :(得分:0)

正确的方法是这样的:

$my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {
  foreach ($my_array_values as $my_array_value) {
    $string_query = $string . $my_array_value . "'";
     echo $string_query . "<br>";
  }
}

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '" ;
my_function ($my_array_values, $string_variable);

答案 2 :(得分:0)

无需在函数中创建额外的变量。只需回显传递的内容以及从传递的数组中提取的值。

$my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {

    foreach ($my_array_values as $my_array_value) {
        echo $string . $my_array_value . "'<br>";
    }

}  // end of my_function

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '";
my_function ($my_array_values, $string_variable);