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


How to dynamically store index of an array element into a variable?

我正在尝试制作一个照片库,其中列出了多个需要分页的画廊。

所以,这个变量

$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(的数字索引到变量中以创建分页函数,因为我需要一个整数值用于此目的。所以,我基本上需要获取数组元素的索引。有没有办法做到这一点?

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

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

只需遍历您的画廊数组并添加 自己设置 id 的值:

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