沃梦达 / 编程问答 / php问题 / 正文

在PHP中循环访问此数组的最佳方式是什么?

What is the best way to loop through this array in PHP?(在PHP中循环访问此数组的最佳方式是什么?)

本文介绍了在PHP中循环访问此数组的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组.如何打印每个文件路径和文件名?执行此操作的最佳方式是什么?

  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 $item[$i]['filename'];
    echo $item[$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是获取数组或对象快照的非常有用的函数。

这篇关于在PHP中循环访问此数组的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在PHP中循环访问此数组的最佳方式是什么?

基础教程推荐