PHP foreach loop through multidimensional array

前端 未结 4 562
死守一世寂寞
死守一世寂寞 2020-11-27 04:39

I have an array:

$arr_nav = array( array( \"id\" => \"apple\", 
          \"url\" => \"apple.html\",
          \"name\" => \"My Apple\" 
        ),
         


        
相关标签:
4条回答
  • 2020-11-27 04:52
    <?php
    $php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
    
    //Iterate through an array declared above
    
    foreach($php_multi_array as $key => $value)
    {
        if (!is_array($value))
        {
            echo $key ." => ". $value ."\r\n" ;
        }
        else
        {
           echo $key ." => array( \r\n";
    
           foreach ($value as $key2 => $value2)
           {
               echo "\t". $key2 ." => ". $value2 ."\r\n";
           }
    
           echo ")";
        }
    }
    ?>
    

    OUTPUT:

    lang => PHP
    type => array( 
        c_type => MULTI
        p_type => ARRAY
    )
    

    Reference Source Code

    0 讨论(0)
  • 2020-11-27 04:55

    If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

    foreach ($arr_nav as $inner_array) {
        echo reset($inner_array); //apple, orange, pear
        echo end($inner_array); //My Apple, View All Oranges, A Pear
    }
    

    arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

    0 讨论(0)
  • 2020-11-27 04:57
    $last = count($arr_nav) - 1;
    
    foreach ($arr_nav as $i => $row)
    {
        $isFirst = ($i == 0);
        $isLast = ($i == $last);
    
        echo ... $row['name'] ... $row['url'] ...;
    }
    
    0 讨论(0)
  • 2020-11-27 05:16
    <?php
    $first = reset($arr_nav); // Get the first element
    $last  = end($arr_nav);   // Get the last element
    // Ensure that we have a first element and that it's an array
    if(is_array($first)) { 
       $first['class'] = 'first';
    }
    // Ensure we have a last element and that it differs from the first
    if(is_array($last) && $last !== $first) {
       $last['class'] = 'last';
    }
    

    Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.

    0 讨论(0)
提交回复
热议问题