我在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。我怎么能这样做?
主要问题是如果实际$services
是foreach循环中最后一个数组的最后一个键,则检查foreach循环内部。
答案 0 :(得分:4)
伙计,为什么不只是end($appointment)['id_services']
?在这种情况下,为什么需要foreach
?
$last_appointment = end($appointment);
$id_services = $last_appointment['id_services'];
$id_services === 13; // true
答案 1 :(得分:1)
你的foreach循环是错误的....
两种简单的方法......
// using count (not recommended)
echo $appointment[count($appointment)-1]['id_services'];
//using end
echo end($appointment)['id_services'];
根据您的评论,您可能会尝试这样做(我不明白为什么)
$last_appointment = end($appointment);
echo end($last_appointment);
修复代码
//not recommended!!
foreach(end($appointment) as $services)
{
print_r(end($services));
}