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

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

php - Loop through a two-dimensional array

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...