1

我正在尝试制作一个包含多个我需要分页的画廊的照片库。

所以,这个变量

$galleries = Photograph::find_by_sql($sql);

持有一个数组:

Array
(
[0] => Photograph Object
    (
        [id] => 
        [gallery_name] => candies
    )

[1] => Photograph Object
    (
        [id] => 
        [gallery_name] => icecream
    )

[2] => Photograph Object
    (
        [id] => 
        [gallery_name] => pastries
    )

[3] => Photograph Object
    (
        [id] => 
        [gallery_name] => chocolate
    )
)

(为方便起见,我把它缩短了)

我正在使用这两个变量来设置选定的画廊:

$newest_gallery = reset($galleries);
$gallery_name = (isset($_GET['subj']) ? $_GET['subj'] : $newest_gallery->gallery_name);

我可以使用gallery_name设置选定的画廊,但是,我无法对画廊进行分页,因为我需要以某种方式将数组元素(保存gallery_name)的数字索引动态存储到变量中以便创建分页功能,因为为此我需要一个整数值。所以,我基本上需要获取数组元素的索引。有没有办法做到这一点?

4

2 回答 2

0

Just loop through your array of galleries and add set the value for id yourself:

$i = 0;
foreach($galleries as $gallery){
    $gallery['id'] = $i;
    $i++;
}
于 2013-10-01T21:21:13.193 回答
0

If I understand your question correctly, you have to make a traverse over the array:

## subj is set - search for it in the array of the objects
if (isset($_GET['subj'])) {
  foreach ($galleries as $id => $gallery) {
    if ($gallery->gallery_name == $_GET['subj']) {
       ## we've found a match - note the id and the name
       $gallery_name = $_GET['subj'];
       $gallery_id =$id;
       break;
    }
  }
}
## if subj was not specified or we found no match in the array 
if (!isset($gallery_id)) {
  reset($galleries);
  $gallery_id = key($galleries);
  $gallery_name = $galleries[$gallery_id]->gallery_name;
}
于 2013-10-01T21:22:09.553 回答