我试图从mysql数据中调用foreach循环中的所有值,并将值输入用于另一个mysql select语句。看下面的代码。它只能收集一个值。我想使用第一个foreach循环包括整个部分,但是,因为foreach值是个体的,我需要爆炸数组为PDO准备。所以,最后,我想知道一种从外部foreach循环中获取所有值的方法。升值。
//mysql connection code, remove because it is not relative to this question
foreach ($tag_id as $term){
$term=$term['term'].' ';//use space to seprate each one
}
echo $term:// only can can one, how can I get all result from above foreach.
$term=explode(' ', $term);
$stm =$db->prepare("SELECT user_id FROM sign WHERE term IN (:term_0,:term_1,:ts.id, s.term, s.counter, os.user_id, os.id, COUNT(oserm_2,:term_3,:term_4,:term_5,:term_6,:term_7,:term_8,:term_9,:term_10)");
$term_0="$term[0]";
$term_1="$term[1]";
$term_2="$term[2]";
$term_3="$term[3]";
$term_4="$term[4]";
//following code is not relevive to this question.
答案 0 :(得分:5)
如果你最后的目的是从你的值创建数组,为什么要将数据附加到字符串,只需将数据添加到数组然后直接使用它。
foreach ($tag_id as $term){
$term_arr[]=$term['term'];
}
print_r($term_arr);
然后你可以使用
$stm =$db->prepare("SELECT user_id FROM sign WHERE term IN (:term_0,:term_1,:ts.id, s.term, s.counter, os.user_id, os.id, COUNT(oserm_2,:term_3,:term_4,:term_5,:term_6,:term_7,:term_8,:term_9,:term_10)");
$term_0="$term_arr[0]";
$term_1="$term_arr[1]";
$term_2="$term_arr[2]";
$term_3="$term_arr[3]";
$term_4="$term_arr[4]";
答案 1 :(得分:5)
假设$ tag_id是mysql查询的数组输出
$t = array();
foreach ($tag_id as $term){
$t[]=$term['term']; // create array of terms
}
$str = "'".implode("','",$t)."'"; // make it a string, you can add here any other string you want to complete your query
$stm =$db->prepare("SELECT `user_id` FROM `sign` WHERE `term` IN (".$str.");
$stm =$db->execute();
答案 2 :(得分:3)
每次你创建循环时,你都会覆盖vale os $ term,请看:
$string = ''
foreach ($tag_id as $term){
$string .= $term['term'] . ' ';//use space to seprate each one
}
$term = $string;
echo $term:// only can can one, how can I get all result from above foreach.
$term=explode(' ', $term);
$stm =$db->prepare("SELECT user_id FROM sign WHERE term IN (:term_0,:term_1,:ts.id, s.term, s.counter, os.user_id, os.id, COUNT(oserm_2,:term_3,:term_4,:term_5,:term_6,:term_7,:term_8,:term_9,:term_10)");
$term_0="$term[0]";
$term_1="$term[1]";
$term_2="$term[2]";
$term_3="$term[3]";
$term_4="$term[4]";
//following code is not relevive to this question.
其他循环:
$string = array();
foreach ($tag_id as $term){
$string[] = $term['term'];
}
$term = $string;