echo key and value of an array without and with loop

前端 未结 11 1954
野的像风
野的像风 2020-12-29 20:47

This is an array i have


How do i get to echo something

相关标签:
11条回答
  • 2020-12-29 21:45

    A recursive function for a change;) I use it to output the media information for videos etc elements of which can use nested array / attributes.

    function custom_print_array($arr = array()) {
        $output = '';
        foreach($arr as $key => $val) {
            if(is_array($val)){
                $output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong><ul class="children">' . custom_print_array($val) . '</ul>' . '</li>';
            }
            else {
                $output .=  '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong> ' . $val . '</li>';
            }
        }
        return $output;
    

    }

    0 讨论(0)
  • 2020-12-29 21:46

    Without a loop, just for the kicks of it...


    You can either convert the array to a non-associative one, by doing:

    $page = array_values($page);
    

    And then acessing each element by it's zero-based index:

    echo $page[0]; // 'index.html'
    echo $page[1]; // 'services.html'
    

    Or you can use a slightly more complicated version:

    $value = array_slice($page, 0, 1);
    
    echo key($value); // Home
    echo current($value); // index.html
    
    $value = array_slice($page, 1, 1);
    
    echo key($value); // Service
    echo current($value); // services.html
    
    0 讨论(0)
  • 2020-12-29 21:50

    You can try following code:

    foreach ($arry as $key => $value) 
    {
          echo $key;
          foreach ($value as  $val) 
          {
             echo $val; 
          }
    }
    
    0 讨论(0)
  • 2020-12-29 21:52

    If you must not use a loop (why?), you could use array_walk,

    function printer($v, $k) {
       echo "$k is at $v\n";
    }
    
    array_walk($page, "printer");
    

    See http://www.ideone.com/aV5X6.

    0 讨论(0)
  • 2020-12-29 21:53
    function displayArrayValue($array,$key) {
       if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
    }
    
    displayArrayValue($page, "Service"); 
    
    0 讨论(0)
提交回复
热议问题