【问题标题】:How to get last array index inside foreach iteration?如何在 foreach 迭代中获取最后一个数组索引?
【发布时间】:2015-11-16 14:18:44
【问题描述】:

我在 StackOverflow 上发现了一些类似的问题,但我的问题不同。我会尽量解释得更清楚。首先是数组结构:$appointment

Array ( 
  [id_users_provider] => 85  
  [start_datetime] => 2015-11-15 17:15:00  
  [end_datetime] => 2015-11-15 17:15:00  
  [notes] =>  
  [is_unavailable] =>  
  [id_users_customer] => 87  
  [id_services] => 15 
)
Array (  
  [id_users_provider] => 85  
  [start_datetime] => 2015-11-15 17:15:00  
  [end_datetime] => 2015-11-15 17:15:00  
  [notes] =>  
  [is_unavailable] =>  
  [id_users_customer] => 87  
  [id_services] => 13  
)

您如何看到我在$appointment 变量中包含了两个数组。现在我想得到最后一个数组的结尾,在本例中是 id_services: 13 的数组。我实际上通过appointment['id_services'] 执行了一次迭代。 像这样:

foreach($appointment['id_services'] as $services)
{
   print_r(end($appointment));
}

但这让我回过神来:

15
13

这是错误的,因为在这种情况下我只想得到 13 个。我怎么能这样做? 主要问题是检查 foreach 循环内部是否实际的 $services 是 foreach 循环内最后一个数组的最后一个键。

【问题讨论】:

  • 使用count()函数知道每个数组中有多少个元素,然后减去一个到那个数字,你会得到最后一个元素
  • 那个循环、结果和解释几乎没有任何意义。

标签: php


【解决方案1】:

伙计,为什么不只是end($appointment)['id_services']?在这种情况下为什么需要foreach

$last_appointment = end($appointment);
$id_services = $last_appointment['id_services'];
$id_services === 13; // true

【讨论】:

  • 怎么为什么?我在 $appointment 变量中有多个数组,我怎么说我必须检查哪个是循环中实际最后一个数组的最后一个键。我不需要检查当前数组的最后一个索引。
  • @Jss“最后一个键”和“最后一个索引”有什么区别?
  • @Jss 你说你不想要1513 输出,只是13,对吧?然后,您使用end() 从源数组中获取最后一个元素,然后您将获得该数组中最后一个键下的值!如果您不知道密钥,请使用 array_keys 函数获取它们并在结果上运行相同的 end 函数。
  • @Jss 如果这不是您想要的结果,您可能需要重新表述您的问题。但是,如果此答案解决了您的问题,您是否可以通过单击答案旁边的绿色复选标记将其标记为已接受?它帮助社区知道这个问题已经得到解决。谢谢!
【解决方案2】:

你的 foreach 循环是错误的......

两种简单的方法...

// using count (not recommended)
echo $appointment[count($appointment)-1]['id_services'];


//using end
echo end($appointment)['id_services'];

根据您的 cmets,您可能正在尝试这样做(我不明白为什么)

$last_appointment = end($appointment);
echo end($last_appointment);

修复你的代码

//not recommended!!
foreach(end($appointment) as $services)
{
   print_r(end($services));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多