简体   繁体   English

如果一个元素在多个数组中相同,则随机选择一个数组?

[英]If an element is the same in more than one array, randomly choose one array?

I have 1 multidimensional array: 我有1个多维数组:

$adverts = array(array('text'=>'test', 'location' => 'location1'), array('text'=>'test', 'location' => 'location2'), array('text'=>'test', 'location' => 'location1'))

As you can see, two arrays inside that multidimensional array contain the same text for the location element. 如您所见,该多维数组内的两个数组包含与location元素相同的文本。

How would I detect this, and randomly choose one of them in a foreach loop that looks something like this: 我将如何检测到它,并在看起来像这样的foreach循环中随机选择其中之一:

foreach ($adverts as $advert)
        {

            if ($hookName == $advert['advert_location'] && XenForo_Helper_Criteria::userMatchesCriteria($advert['user_criteria']))
            {
                $contents .= $advert['advert_code'];
            }
        }

(I know the arrays don't match) (我知道数组不匹配)

In that foreach loop, each the location of each array in the multidimensional array is being checked against a predefined value. 在该foreach循环中,将对照预定义值检查多维数组中每个数组的每个location If more than one of the array's inside the multidimensional array have the same location I want to only use one of them - in other words, contents doesn't get modified for the same location more than once. 如果多维数组中多个数组中的一个具有相同的location我只想使用其中一个-换句话说,对于同一位置,内容不会被修改多次。

However, it should use a random array from each of the matching values. 但是,它应该使用每个匹配值中的随机数组。

Is this possible, did you understand it and how would it be done? 这可能吗,您了解吗?如何实现?

Just group them bases on location then select at random each time you loop 只需根据位置将它们分组,然后在每次循环时随机选择

$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);

See Example 参见示例

You can use array_filter to filter out only the elements that match your criteria, then use array rand to select a random one. 您可以使用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;
 }

Note this requires php 5.3 请注意,这需要php 5.3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM