dtqu72830 2012-09-11 17:31
浏览 61
已采纳

printf问题与数组

So i have a problem with taking an array and looping through the values and outputing with a foreach statement.

code

<?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"]);
}

?>

hoping to get the output:

what do you have to say for yourself?

hello world!

Instead get

what do you have to say for yourself?

h!

why just the single character?

Any help would be great

thanks

  • 写回答

4条回答 默认 最新

  • doudichu1358 2012-09-11 17:33
    关注

    Your foreach loop is already going through the values of the array, so don't reference the value again using the key:

    <?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);
    }
    
    ?>
    

    From your other example in the comments, you would not be able to use a loop because the placements are very specific. Instead reference each value specifically without a loop:

    $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']
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁
  • ¥15 bywave配置文件写入失败
  • ¥20 基于Simulink的ZPW2000轨道电路仿真