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

时间:2015-11-15 16:09:54

标签: 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] =>  
  [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。我怎么能这样做?

5 个答案:

答案 0 :(得分:1)

以下代码假定$services仅为数字。它迭代所有数字,检查当前是否大于$m并最终存储新的$m

$m = 0;
foreach($appointment['id_services'] as $services)
    $m = ($services > $m)?$services:$m;

// after the iteration $m has the maximum value
echo $m;

编辑:要获得最后(不一定是最好的),你可以做某事。像这样:

$c = count($appointment['id_services']);
$l = $appointment['id_services'][$c-1]; // 13

答案 1 :(得分:0)

你能不做这样的事吗?

$appointments=array( 
    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 )
);

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

答案 2 :(得分:0)

男人,要获得你做end($array)数组的最后一个元素。在你的情况下它是end($appointments)。在获得最后一个元素之后,这又是一个带有键'id_service'等的关联数组,您只需获得所需的值,例如end($appointments)['id_service'],即所有,什么'错了吗?

答案 3 :(得分:0)

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,你可以保证这个密钥永远是最后一个,只需按照以下方式引用它;

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

答案 4 :(得分:0)

从PHP 7.3开始,您可以使用array_key_last函数。

$last_key = array_key_last($array);