drtkyykai004574380 2013-10-01 19:26
浏览 73
已采纳

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

I'm trying to make a photo gallery with multiple galleries listed that I need to paginate.

So, this variable

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

holds an array:

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
    )
)

(I've shortened it for convenience)

I'm using these two variables to set a selected gallery:

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

I was able to set the selected gallery by using the gallery_name, however, I'm unable to paginate the galleries since I need to somehow dynamically store a numerical index of an array element (which holds the gallery_name) into a variable in order to create the pagination function, since I need an integer value for this purpose. So, I basically need to get the index of an array element. Is there a way to do this?

  • 写回答

2条回答 默认 最新

  • duanbin4847 2013-10-01 21:22
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办