私はこの配列を持っています...ファイルパスとファイル名のそれぞれをどのように印刷しますか?これを行う最良の方法は何ですか?
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
は、配列またはオブジェクトのスナップショットを取得するのに非常に便利な関数です。
OK
array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);
またはより複雑な方法で:
function printItem($n){
echo $n['filename'];
echo $n['filepath'];
}
array_map('printItem', $array);
これにより、データをより簡単に操作できるようになります。
HTMLを使用せずにシンプルに開始:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
それ以外の場合は、foreachのフィールドを操作できます。
foreach($array as $item=>$values){
echo $values->filepath;
}