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

Php 如何将数组元素的索引动态存储到变量中?,php,arrays,Php,Arrays,我正在尝试创建一个照片库,其中列出了我需要分页的多个库 所以,这个变量 $galleries=photo::按搜索sql$sql查找搜索 保存一个数组: Array ( [0] => Photograph Object ( [id] => [gallery_name] => candies ) [1] => Photograph Object ( [id] => [gall

我正在尝试创建一个照片库,其中列出了我需要分页的多个库

所以,这个变量

$galleries=photo::按搜索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_名称设置选定的库,但是,我无法对库进行分页,因为我需要以某种方式动态存储数组元素的数字索引,该数组元素将库名称保存到变量中,以便创建分页函数,因为我需要一个整数值。
所以,我基本上需要得到数组元素的索引。有什么方法可以做到这一点吗?

只需在你的图库数组中循环并添加设置id值:

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

如果我正确理解您的问题,您必须遍历阵列:

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

用钥匙?这不好。它返回索引元素。我需要数组元素的索引号。括号里的数字。你读过链接吗?读过。也许我在这里误解了什么,但在我的例子中,key返回id,id是数组对象的索引元素。身份证对我没有好处,因为那些是照片的身份证,而不是画廊的身份证。每个图库中都有几十个ID。我需要得到每个数组对象的索引号。我该怎么做?