Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an array that looks like this:

$array = array(
    array(
        "http://google.com",
        "Google"
    ),

    array(
        "http://yahoo.com",
        "Yahoo"
    )
);

What is the simplest way to loop through it. Something like:

foreach ($array as $arr) {
    // help
}

EDIT: How do I target keys, for example, I want to do:

foreach ($array as $arr) {
    echo '<a href" $key1 ">';
    echo ' $key2 </a>';
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use nested foreach() because it is 2D array. Example here

foreach($array as $key=>$val){ 
    // Here $val is also array like ["Hello World 1 A","Hello World 1 B"], and so on
    // And $key is index of $array array (ie,. 0, 1, ....)
    foreach($val as $k=>$v){ 
        // $v is string. "Hello World 1 A", "Hello World 1 B", ......
        // And $k is $val array index (0, 1, ....)
        echo $v . '<br />';
    }
}

In first foreach() $val is also an array. So a nested foreach() is used. In second foreach() $v is string.

Updated according to your demand

foreach($array as $val){
    echo '<a href="'.$val[0].'">'.$val[1].'</a>';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...