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 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?