[英]Having trouble with a very simple PHP array issue
All I need to two is remove the final two elements from an array, which only contains 3 elements, output those two removed elements and then output the non-removed element. 我需要的两个是从数组中删除最后两个元素,它只包含3个元素,输出这两个被删除的元素,然后输出未删除的元素。 I'm having trouble removing the two elements, as well as keeping their keys.
我在删除这两个元素时遇到了麻烦,并且保留了它们的密钥。
My code is here http://pastebin.com/baV4fMxs 我的代码在这里http://pastebin.com/baV4fMxs
It is currently outputting : Java Perl Array 它目前正在输出:Java Perl Array
I want it to output: [One] => Perl and [Two] => Java [Zero] => PHP 我希望它输出:[One] => Perl和[Two] => Java [Zero] => PHP
$last=array_splice($inputarray,-1);
//$last has now key=>value of last element
$middle=array_splice($inputarray,-1);
//$middle has now key=>value of middle element
//$inputarray has now only key=>value of first element
You mentioned keys, so I assume it's an associative array. 你提到了键,所以我认为它是一个关联数组。 In order to remove an element, you can call the
unset
function, like this: 要删除元素,可以调用
unset
函数,如下所示:
unset ($my_array['my_key'])
Do this for both elements that you want to remove. 对要删除的两个元素执行此操作。
It seems to me that you want to retrieve those two values being removed before getting rid of them. 在我看来,你想要在删除它们之前检索被删除的那两个值。 With this in mind, I suggest the use of
array_pop()
which simultaneously returns the last item in the array and removes it from the array. 考虑到这一点,我建议使用
array_pop()
同时返回数组中的最后一项并将其从数组中删除。
$val = array_pop($my_array);
echo $val; // Last value
$val = array_pop($my_array);
echo $val; // Middle value
// Now, $my_array has only the first value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.