dongtan6206 2015-11-04 15:50
浏览 30

PHP多维数组foreach echo值

I'm having a hard time wrapping my head around this one. I have an array with different keys/values, I want to do a loop that allows me to put in different code wrappings. I'm working with an array that I'm trying to get as an XML.

This is an example of what I have.. I have what came with the code commented out and what I'm trying to do just below it in the foreach

// Multidimensional array
$superheroes = array(
    "spider-man" => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        ),
    "super-man" => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        ),
    "iron-man" => array(
        "name" => "Harry Potter",
        "email" => "harrypotter@mail.com",
        )
    );

// Printing all the keys and values one by one
    $keys = array_keys($superheroes);
    for($i = 0; $i < count($superheroes); $i++) {
        echo $keys[$i] . "{<br>";
        foreach($superheroes[$keys[$i]] as $key => $value) {
            // echo $key . " : " . $value . "------";
            echo '<wp:meta_key>'.$value['email'].'<wp:meta_key>';
            echo '<wp:meta_value><![CDATA['.$value['name'].']]></wp:meta_value>';
        }
        echo "}<br>";
    }
  • 写回答

1条回答 默认 最新

  • duanbi1888 2015-11-04 15:56
    关注

    This is how you iterate the array, two levels deep:

    foreach($superheroes as $key => $hero) {
        echo $key."
    ";
        foreach ($hero as $heroKey => $heroValue) {
            echo "\t".$heroKey."=>".$heroValue."
    ";
        }
    }
    

    You will have to adjust it to your output, but im showing the concept. The first foreach iterates all the heroes, and the second foreach iterates all the key/value pairs of each hero

    EDIT: Hold on, its a bit unclear what you actually want. Is this what you want?

    foreach($superheroes as $key => $hero) {
        echo $key."
    ";
        echo "\t".$hero['email']."
    ";
        echo "\t".$hero['name']."
    ";
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等