开发者

Copy last 4 array keys and values and add them onto end of the same array but with a different key name

I've looked at other questions and answers, but nothing quite helps me with this.

I've got an array of items for example like this (the amount of items varies):

'harry' => 'dog',
'bob' => 'badger',
'george' => 'toad',
'fred' => 'frog',
'lucy' => 'bird',
'melanie' => 'cat'

and what i'd like to do is to always take the last 4 items from the array (no matter how big the array is, bearing in mind that it is variable in the amount of items that will be in it), copy them, give each key a different name, but retain the values. So the array would end up like this:

'harry' => 'dog',
'bob' => 'badger',
'george' => 'toad',
'fred' => 'frog',
'lu开发者_如何学JAVAcy' => 'bird',
'melanie' => 'cat'
'adam' => 'toad',
'becca' => 'frog',
'tom' => 'bird',
'dave' => 'cat'

Thanks very much indeed for any help anyone can give me!


array_slice($array, -4) will give you the last 4 values of $array. You can then use array_combine to get a new array with these same values and the keys of your choice. Finally, use the union operator to append the new key/value pairs to the end of the original array.

See it in action.

You could also take a number of other approaches, but I believe this one is both short and easily understandable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜