printf问题与数组

时间:2012-09-11 17:31:41

标签: php

所以我在获取数组并循环遍历值并使用foreach语句输出时遇到问题。

<?php
$example = array("test" => "hello world" );

foreach ($example as $arr) {
  printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$arr["test"]);
}

?>

希望得到输出:

你要为自己说些什么?

你好世界!

取而代之的是

你要为自己说些什么?

ħ!

为什么只是单个角色?

任何帮助都会很棒

感谢

4 个答案:

答案 0 :(得分:4)

你的foreach循环已经遍历数组的值,所以不要使用键再次引用该值:

<?php
$example = array("test" => "hello world" );

foreach ($example as $key => $val) {
  printf("<p>what do you have to say for yourself?</p><p>%s!</p>",$val);
}

?>

从评论中的其他示例中,您将无法使用循环,因为展示位置非常具体。而是在没有循环的情况下专门引用每个值:

$example = array(
    "first" => "Bob", 
    "last" => "Smith", 
    "address" => "123 Spruce st"
);
printf("<p>my name is %s %s and i live at %s</p>", 
    $example['first'], 
    $example['last'], 
    $example['address']
);

答案 1 :(得分:1)

或许以这种方式看待它会有所帮助;

<?php 
$example = array("test" => "hello world", "foo" => "bar"); 

foreach ($example as $key => $val) { 
# option 1
    echo "<p>what do you have to say for yourself?</p><p>$key => $val</p>"; 
# option 2
    echo "<p>what do you have to say for yourself?</p><p>$key => $example[$key]</p>"; 
} 
?> 

一旦你看到它如何迭代,你可以将你的语句放回到printf()或对变量做任何事情。

请注意,如果您有多维数组,则可以通过寻址键来引用数组的下一级;

答案 2 :(得分:0)

循环关联数组会在每次迭代中将值放入$arr。当你尝试索引到$ arr时,你实际上是索引到一个字符串,因此是单个字符。

答案 3 :(得分:0)

Foreach假设数组中有多个元素。如果不是像echo $ example ['test']那样回显元素;不需要循环结构。如果有多个元素:

$example = array('text'=>"what do you have to say for yourself?",'test' => "hello world" );

print_r($example);

foreach ($example as $value)  
printf("<p>%s!</p>",$value);

foreach将数组元素的值赋给每个循环上名为$ value的变量。有意义吗?