考虑以下数组
$array = array('fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese');
我想用数组弹出 http://php.net/manual/en/function.array-pop.php得到最后一个核心价值 pair.
然而,人们会注意到,在执行以下操作之后
$last = array_pop($array);
var_dump($last);
它将仅输出值(string(6) "cheese"
)
如何从数组中“弹出”最后一对,保留键/值数组结构?
查看array_slice()
http://php.net/manual/en/function.array-slice.php http://php.net/manual/en/function.array-slice.php
最后一个论点true
是保存密钥。
当您将偏移量传递为负数时,它会从末尾开始。这是一个很好的技巧,可以在不计算总数的情况下获取最后一个元素。
$array = [
"a" => 1,
"b" => 2,
"c" => 3,
];
$lastElementWithKey = array_slice($array, -1, 1, true);
print_r($lastElementWithKey);
Outputs:
Array
(
[c] => 3
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)