在这种情况下,如何获得外部 foreach 循环值?
Posted
技术标签:
【中文标题】在这种情况下,如何获得外部 foreach 循环值?【英文标题】:How can I get outside foreach loop value in this situation? 【发布时间】:2015-05-06 07:57:42 【问题描述】:我正在尝试从 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.
【问题讨论】:
$terms .= $term['term'].' ';
而不是 $term=$term['term'].' ';
。注意.=
php.net/manual/en/language.operators.string.php。但是由于您只是希望它们在一个数组中,只需执行$terms[]=$term['term'];
,然后它就全部在一个数组中,而不必使用$term=explode(' ', $term);
为什么不使用 SQL 连接?
【参考方案1】:
如果您的最后一个目的是从您的值创建一个数组,为什么要将数据附加到一个字符串,只需将您的数据添加到一个数组然后直接使用它。
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]";
【讨论】:
【参考方案2】:假设 $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();
【讨论】:
【参考方案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;
【讨论】:
以上是关于在这种情况下,如何获得外部 foreach 循环值?的主要内容,如果未能解决你的问题,请参考以下文章
如果在foreach循环下动态生成Textarea不止一次,如何在Razor(blazor)组件中获取Textarea值