如何回显foreach循环的每个值?

时间:2011-08-10 22:14:54

标签: php html

不确定问题标题是否真的有意义。

无论如何,我想做的是能够从foreach循环中回显单个值。

这是我的代码:

$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
  foreach($headlines as $headline) {
      $headline = str_replace($searches, $replacements, $headline);
      echo($headline['primary_headline']); // I thought this would do the trick
  }
}

我认为这会在发布my city is Dallas时回复my city is $city_name,不幸的是,事实并非如此,它只是回应msps,这是每个{1}的第一个字母输入值:

<input name="primary_headline" type="text" value="my city is $city_name" />
<input name="secondary_headline" type="text" value="secondary headline" />
<input name="primary_subline" type="text" value="primary subline" />
<input name="secondary_subtext" type="text" value="secondary subline" />
<input type="submit" value="submit" />

如果有人能指出我正确的方向,我将非常感谢!! :)

4 个答案:

答案 0 :(得分:2)

更改

echo($headline['primary_headline']); // I thought this would do the trick

echo($headline) . PHP_EOL; // I thought this would do the trick

当你使用foreach时,你不需要为元素指定一个索引,因为foreach将为你处理迭代,所以当你在循环中取消引用某些东西时,你要求字符串中的一个字符。这里你得到第一个字符,因为'primary_headline'被解释为0。

答案 1 :(得分:2)

$searches = array('$city_name', '$ref_name');

单引号使$ search实际上包含单词$city_name,而不是$ city_name的VALUE。分配变量时不需要引号:

$searches = array($city_name, $ref_name);

当然,除非您正在使用某种模板系统并尝试在没有eval()的情况下进行变量插值。

答案 2 :(得分:1)

$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);

这会创建一个具有key=>value对的数组,而不是多维数组。在foreach循环中循环遍历此数组将仅返回值,即第一次迭代的$_POST['primary_headline'],第二次迭代的$_POST['secondary_headline']等。这就是您无法访问的原因$headline['primary_headline']

如果您想根据您的示例访问“我的城市是达拉斯”,只需回复$headlines['primary_headline']

如果您想回显每个值:

foreach($headlines as $headline) {
  echo $headline . PHP_EOL;
}

答案 3 :(得分:0)

如果有好的衡量标准,我应该用一个答案来结束这个问题(我已经把它放在评论部分,因为我无法添加答案)。

必须使用&符号(&amp;)来分配对原始数组$headlines的引用,而不是复制它的贵重物品,从而使用foreach()循环内创建的任何值更新它。 / p>

所以,我的代码现在是;

$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
  foreach($headlines as &$headline) {
      $headline = str_replace($searches, $replacements, $headline);
  }
echo ($headlines['primary_headline']) // This now has the value of $_POST['primary_headline'] along with the str_replace() function assigned to $headline  
}