gpt4 book ai didi

php - 如何获取最后一个数组索引?

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:49 25 4
gpt4 key购买 nike

我在 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。我该怎么做?

最佳答案

Get the last array index

只需反转数组,然后使用end

echo end(array_keys($s));

Get all contents of the last array index

通过迭代简单地使用end

foreach($appointments as $app) {
echo end($app) . PHP_EOL;
}

Get only the last element from the sub-array (只输出13)

简单地获取最后一个子数组并将其放入end

echo end($appointments[ count($appointments) - 1 ]);

如果你只想获取 id_services,因为你不能保证这个 key 永远是最后一个,只需按如下方式引用它;

echo $appointments[ count($appointments) - 1 ]['id_services'];

关于php - 如何获取最后一个数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33721812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com