Loop through an array php

前端 未结 5 841
故里飘歌
故里飘歌 2020-11-22 17:13

I have this array... how do you print each of the filepath and filename? What is the best way to do this?

  Array ( 
    [0] => Array ( 
             [fid         


        
相关标签:
5条回答
  • 2020-11-22 17:42

    Starting simple, with no HTML:

    foreach($database as $file) {
        echo $file['filename'] . ' at ' . $file['filepath'];
    }
    

    And you can otherwise manipulate the fields in the foreach.

    0 讨论(0)
  • 2020-11-22 17:43
    foreach($array as $item=>$values){
         echo $values->filepath;
        }
    
    0 讨论(0)
  • 2020-11-22 17:49

    Using foreach loop without key

    foreach($array as $item) {
        echo $item['filename'];
        echo $item['filepath'];
    
        // to know what's in $item
        echo '<pre>'; var_dump($item);
    }
    

    Using foreach loop with key

    foreach($array as $i => $item) {
        echo $item[$i]['filename'];
        echo $item[$i]['filepath'];
    
        // $array[$i] is same as $item
    }
    

    Using for loop

    for ($i = 0; $i < count($array); $i++) {
        echo $array[$i]['filename'];
        echo $array[$i]['filepath'];
    }
    

    var_dump is a really useful function to get a snapshot of an array or object.

    0 讨论(0)
  • 2020-11-22 17:49

    You can use also this without creating additional variables nor copying the data in the memory like foreach() does.

    while (false !== (list($item, $values) = each($array)))
    {
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 17:53

    Ok, I know there is an accepted answer but… for more special cases you also could use this one:

    array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);
    

    Or in a more un-complex way:

    function printItem($n){
        echo $n['filename'];
        echo $n['filepath'];
    }
    
    array_map('printItem', $array);
    

    This will allow you to manipulate the data in an easier way.

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