开发者

What is the best way in PHP to reduce an array by an array of known keys?

I am browsing the array functions in PHP, trying to find the magical wand(s) to do this.

Here is what I have.

$images = array(...);

$randomImages = array_rand($images, 3);

// Now I want to reduce $images by the keys in $randomImages

What PHP array functions can I leverage for this?

Update

I ended up answering my own question after digging for a while, but I'm still open to alternate开发者_如何学JAVA solutions :)


I came up with this, and it works well...

$images = array_intersect_key($images, array_flip($randomImages));

I can also do it using...

shuffle($images);
$images = array_slice($images, 0, 3);

(This uses Andre's answer as a basis).


I would suggest a different approach just because it fits in one line:

$images = array_intersect_key($images, array_slice(shuffle(array_keys($images)), 0, 3));

I like one-liners.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜