如何设置最后一个索引键


How to set last index key

我想知道如何在从SIMPLEXML响应中获取价格的以下代码中设置最后一个索引键(而不需要事先知道它是什么):

$product_price = $CATEGORIES->PRODUCTS->PRICES->PRICE[0]->AMOUNT;

可能有不止一个价格,所以有时有3个,有时有5个等等。但我只想得到最后一个,所以PRICE[0]中的密钥需要动态地获取最后一个。

如何做到这一点?

谢谢。

您可以使用end()来获取数组中的最后一个元素。

$prices = $CATEGORIES->PRODUCTS->PRICES;
$last_price = end($prices);
$amount = $last_price->AMOUNT;

您可以使用array_pop()

像这样:

$array = array('a','b','c');
// This get the value and remove it from the end of the array
$test1 = array_pop($array);
// This will only get the value from the array
$array[] = $test2 = array_pop($array);
var_dump($test1); // "c"
var_dump($test2); // "b"
var_dump($array); // array('a', 'b')