Loop through a two-dimensional array

2020-02-15 08:43发布

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

5条回答
太酷不给撩
2楼-- · 2020-02-15 09:05

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>';
}
查看更多
做个烂人
3楼-- · 2020-02-15 09:05

The way to loop through is,

foreach($array as $arr)
foreach($arr as $string) {
        //perform any action using $string
}

Use the first foreach loop without { } for the simplest use.

That can be the most simple method to use a nested array as per your request.

For your edited question.

Wrong declaration of array for using key.

$array = array( 
    "http://google.com" => "Google",
    "http://yahoo.com" => "Yahoo" );

And then, use the following.

foreach ($array as $key => $value)
    echo "<a href='{$key}'>{$value}</a>";

This doesn't slow down your server's performance.

查看更多
手持菜刀,她持情操
4楼-- · 2020-02-15 09:11

First modify your variable like this:

$array = array(
          array("url"=>"http://google.com",
                "name"=>"Google"
          ),
          array("url"=>"http://yahoo.com",
                "name"=>"Yahoo"
          ));

then you can loop like this:

foreach ($array as $value)
{ 
   echo '<a href='.$value["url"].'>'.$value["name"].'</a>'
}
查看更多
女痞
5楼-- · 2020-02-15 09:18

In order to echo out the bits you have to select their index in each array -

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

Here is an example.

查看更多
对你真心纯属浪费
6楼-- · 2020-02-15 09:26

The easiest way to loop through it is:

foreach ($array as $arr) {
    foreach ($arr as $index=>$value) {
        echo $value;
    }
}

EDIT:

If you know that your array will have always only two indexes then you can try this:

foreach ($array as $arr) {
    echo "<a href='$arr[0]'>$arr[1]</a>";
}
查看更多
登录 后发表回答