PHP:显示单个数组数据


PHP: Displaying single array data?

所以代码是

$gallery = get_gallery('gallery_id');
print_r ($gallery);

得到:

Array ( [0] => Array ( [id] => 13 [image] => 0 [user] => 13 [timestamp] => 1366237591 [ext] => png [caption] => Happy smile shi ma? [comment] => ) [1] => Array ( [id] => 14 [image] => 0 [user] => 13 [timestamp] => 1366237954 [ext] => jpg [caption] => Confused [comment] => ) [2] => Array ( [id] => 15 [image] => 0 [user] => 13 [timestamp] => 1366237979 [ext] => jpg [caption] => Facebookerg [comment] => ) [3] => Array ( [id] => 16 [image] => 0 [user] => 13 [timestamp] => 1366377510 [ext] => gif [caption] => lolwut? [comment] => ) [4] => Array ( [id] => 17 [image] => 0 [user] => 13 [timestamp] => 1366380899 [ext] => jpg [caption] => rorwut? [comment] => ) [5] => Array ( [id] => 18 [image] => 0 [user] => 13 [timestamp] => 1366651685 [ext] => jpg [caption] => Notes? [comment] => ) [6] => Array ( [id] => 19 [image] => 0 [user] => 13 [timestamp] => 1366711880 [ext] => jpg [caption] => asd [comment] => ) [7] => Array ( [id] => 20 [image] => 0 [user] => 14 [timestamp] => 1366940983 [ext] => jpg [caption] => Belzelga [comment] => ) )

这很好,它终于工作了。但是如何显示单个数据/表呢?因为我试图从这些东西中获得一个单一的"id"。我试着回显$gallery['id']但是我得到了一个错误。:/

您需要首先访问正确的索引:

$gallery[0]['id']
//      ^^^

你的$gallery变量现在是一个多维数组。

$gallery[0]['id'];
$gallery[1]['id'];
.....

现在您可以使用foreach来遍历数组或使用for循环

foreach ($gallery as $anItem ) {
    echo $anItem['id'];
}

for ( $x=0; $x < count($gallery); $x++ ) {
    echo $gallery[$x]['id'];
}

试试这个循环代码段:

foreach( $gallery as $temp ) {
    echo $temp['id'];
}

$gallery是一个多维数组。您需要遍历它

如果您只想显示一个特定的图库,您可能应该使用类似www.yoursite.com/gallery.php?id=1的东西。然后在代码中显示它

    if(isset($_GET['id']))
    {
         foreach( $gallery as $g ) 
         {
           if($g['id'] == $_GET['id'])
                 echo $g['id'];
         }
    }

您可以这样获取数据。

current($gallery)['id']