[英]If an element is the same in more than one array, randomly choose one array?
我有1个多维数组:
$adverts = array(array('text'=>'test', 'location' => 'location1'), array('text'=>'test', 'location' => 'location2'), array('text'=>'test', 'location' => 'location1'))
如您所见,该多维数组内的两个数组包含与location
元素相同的文本。
我将如何检测到它,并在看起来像这样的foreach循环中随机选择其中之一:
foreach ($adverts as $advert)
{
if ($hookName == $advert['advert_location'] && XenForo_Helper_Criteria::userMatchesCriteria($advert['user_criteria']))
{
$contents .= $advert['advert_code'];
}
}
(我知道数组不匹配)
在该foreach循环中,将对照预定义值检查多维数组中每个数组的每个location
。 如果多维数组中多个数组中的一个具有相同的location
我只想使用其中一个-换句话说,对于同一位置,内容不会被修改多次。
但是,它应该使用每个匹配值中的随机数组。
这可能吗,您了解吗?如何实现?
只需根据位置将它们分组,然后在每次循环时随机选择
$group = array_reduce($adverts, function ($a, $b) {
$a[$b['location']][] = $b;
return $a;
});
$contents = array();
foreach($group as $adverts) {
$contents[] = $adverts[mt_rand(0, count($adverts) - 1)];
}
print_r($contents);
您可以使用array_filter仅过滤出符合条件的元素,然后使用array rand选择一个随机元素。
$array = array_filter($array, function($el) use $location{
return $el["location"] == $location;
});
if (count($array) > 1){
$selected = $array(array_rand($array));
} elseif (count($array) == 0){
$selected = $array[0];
} else {
$selected = null;
}
请注意,这需要php 5.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.