简体   繁体   中英

PHP multidimensional array foreach echo value

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>";
    }

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

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

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."\n";
    echo "\t".$hero['email']."\n";
    echo "\t".$hero['name']."\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM