Php 如何在foreach迭代中获取最后一个数组索引?
我在StackOverflow上发现了一些类似的问题,但我的问题不同。我会尽量解释得更清楚一些。首先是数组结构:Php 如何在foreach迭代中获取最后一个数组索引?,php,Php,我在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] =>
$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的数组。实际上,我通过约会['id\u services']
执行了一次迭代。
像这样:
foreach($appointment['id_services'] as $services)
{
print_r(end($appointment));
}
但这让我回想起:
1513
这是错误的,因为在这种情况下我只想得到13分。我怎么能做到?
主要问题是在foreach循环内检查实际的
$services
是否是foreach循环内最后一个数组的最后一个键。伙计,为什么不干脆结束($appointment)['id\u services']
?在这种情况下,为什么需要一个foreach
$last_appointment = end($appointment);
$id_services = $last_appointment['id_services'];
$id_services === 13; // true
伙计,为什么不干脆
结束($appointment)['id\u services']
?在这种情况下,为什么需要一个foreach
$last_appointment = end($appointment);
$id_services = $last_appointment['id_services'];
$id_services === 13; // true
您的foreach循环是错误的 两种简单的方法
// using count (not recommended)
echo $appointment[count($appointment)-1]['id_services'];
//using end
echo end($appointment)['id_services'];
根据您的评论,您可能正在尝试这样做(我不明白为什么)
修正你的代码
//not recommended!!
foreach(end($appointment) as $services)
{
print_r(end($services));
}
您的foreach循环是错误的 两种简单的方法
// using count (not recommended)
echo $appointment[count($appointment)-1]['id_services'];
//using end
echo end($appointment)['id_services'];
根据您的评论,您可能正在尝试这样做(我不明白为什么)
修正你的代码
//not recommended!!
foreach(end($appointment) as $services)
{
print_r(end($services));
}
使用
count()
函数知道每个数组中有多少个元素,然后将其中一个减去该数字,您将得到最后一个元素。循环、结果和解释几乎没有任何意义。使用count()
函数知道每个数组中有多少元素,然后把一减到那个数,你会得到最后一个元素,循环,结果和解释几乎没有任何意义。为什么?$appointment变量中有多个数组,我是如何说我必须检查循环中最后一个数组的最后一个键的。我不需要检查当前数组的最后一个索引。@Jss“最后一个键”和“最后一个索引”有什么区别?@Jss你说你不想要15
,13
输出,只要13
,对吗?然后,使用end()
从源数组中获取最后一个元素,然后获取该数组中最后一个键下的值!如果您不知道这些键,请使用array\u keys
函数获取它们,并对结果运行相同的end
函数。@Jss如果这不是您想要的结果,您可能需要重新表述您的问题。但是,如果此答案解决了您的问题,您能否通过单击答案旁边的绿色复选标记将其标记为已接受?这有助于社区了解这个问题已经得到解决。谢谢为什么?$appointment变量中有多个数组,我是如何说我必须检查循环中最后一个数组的最后一个键的。我不需要检查当前数组的最后一个索引。@Jss“最后一个键”和“最后一个索引”有什么区别?@Jss你说你不想要15
,13
输出,只要13
,对吗?然后,使用end()
从源数组中获取最后一个元素,然后获取该数组中最后一个键下的值!如果您不知道这些键,请使用array\u keys
函数获取它们,并对结果运行相同的end
函数。@Jss如果这不是您想要的结果,您可能需要重新表述您的问题。但是,如果此答案解决了您的问题,您能否通过单击答案旁边的绿色复选标记将其标记为已接受?这有助于社区了解这个问题已经得到解决。谢谢