如何将数组元素的索引动态存储到变量中?

时间:2013-10-01 19:26:51

标签: php arrays

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

所以,这个变量

$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)的数字索引动态存储到变量中为了创建分页功能,因为我需要一个整数值来达到这个目的。 所以,我基本上需要获取数组元素的索引。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

只需遍历您的图库数组并自行添加设置id的值:

$i = 0;
foreach($galleries as $gallery){
    $gallery['id'] = $i;
    $i++;
}

答案 1 :(得分:0)

如果我理解你的问题,你必须遍历数组:

## 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;
}