[英]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. 我正在浏览PHP中的数组函数 ,试图找到执行此操作的魔术棒。
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? 为此,我可以利用哪些PHP数组函数?
I ended up answering my own question after digging for a while, but I'm still open to alternate 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. 我喜欢单线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.