循环一个数组php

我有这个数组…如何打印每个文件path和文件名? 什么是最好的方法来做到这一点?

Array ( [0] => Array ( [fid] => 14 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => trucks_10785.jpg [filepath] => sites/default/files/trucks_10785.jpg [filemime] => image/jpeg [filesize] => 143648 [status] => 1 [timestamp] => 1291424171 [nid] => 8 ) [1] => Array ( [fid] => 19 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => school.jpg [filepath] => sites/default/files/school.jpg [filemime] => image/jpeg [filesize] => 115355 [status] => 1 [timestamp] => 1292029563 [nid] => 8 ) [2] => Array ( [fid] => 20 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => Life_is_wonderful_by_iNeedChemicalX.jpg [filepath] => sites/default/files/Life_is_wonderful_by_iNeedChemicalX_0.jpg [filemime] => image/jpeg [filesize] => 82580 [status] => 1 [timestamp] => 1292029572 [nid] => 8 ) [3] => Array ( [fid] => 21 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => school_rural.jpg [filepath] => sites/default/files/school_rural.jpg [filemime] => image/jpeg [filesize] => 375088 [status] => 1 [timestamp] => 1292029582 [nid] => 8 ) ) 

使用没有密钥的foreach循环

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

用键使用foreach循环

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

使用for循环

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

var_dump是一个非常有用的函数来获取数组或对象的快照。

从简单的开始,没有HTML:

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

你也可以用foreach来操纵这些字段。

好吧,我知道有一个被接受的答案,但是…对于更特殊的情况,你也可以使用这个:

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

或者以更复杂的方式:

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

这将允许您以更简单的方式操作数据。