php 数组中的随机元素没有兄弟姐妹

php random element from array no siblings

尝试从数组 ($colors) 中随机获取一个项目,而不是两个相同的颜色彼此相邻。

<div class="list">
  <?php
  foreach ($team as $member):
    $index++;
  ?>
  <div class="member location-<?php echo strtolower($member->location); ?>">
    <a style="background: #FFF url('<?php echo $member->profileImage; ?>') no-repeat;" data-start-date="<?php echo $member->startDate; ?>">
      <?php shuffle($colors); // Shuffle the array ?>
      <span class="name" style="background-color: #<?php echo array_pop($colors)->color; ?>"><?php echo $member->name; ?></span>
      <span class="job-title"><span class="text"><?php echo $member->jobTitle; ?></span></span>
    </a>
  </div>
  <?php endforeach; ?>
</div>

现在我有一些情况,我得到的颜色彼此相邻。

如何每次获得不同的颜色?我想提一下 count($team) > count($colors)(更大)。

更新:

$colors 看起来像(我刚打印了 3 件,数量更高)

    array(18) {
      [0]=>
      object(stdClass)#112 (1) {
        ["color"]=>
        string(6) "5ebedb"
      }
      [1]=>
      object(stdClass)#111 (1) {
        ["color"]=>
        string(6) "c75d40"
      }
      [2]=>
      object(stdClass)#110 (1) {
        ["color"]=>
        string(6) "faaf37"
    }
  }

这不是真正随机的,因为以防万一您再次使用相同的颜色 我们必须进行数学计算才能得到另一种颜色。 我们可以使用运行 rand 函数的 while 循环,但我认为它效率不高,尤其是当我们讨论为视觉目的获取随机颜色时。

不是最明智的解决方案,但我相信它可以完成这项工作。

$colors = array('blue','red','green');

function getRandomColor($colors, $lastIndex = null){
  $rand = floor(rand(0, count($colors)));
  if(isset($lastIndex) && $rand == $lastIndex){
    if($rand == 0)
      $rand++;
    else //prevent offset: ($rand == count($colors))
      $rand--;
  }
    return array('color' => $colors[$rand], 'lastIndex' => $rand);
}

使用方法,第一次使用:

$rand_color = getRandomColor($colors);

并且在第一个循环之后使用:

$rand_color = getRandomColor($colors, $rand_color['lastIndex']);

您可以简单地使用一个简单的条件来检查 $rand_color 是否已经设置。

<?
$color1 = array(); 

  foreach ($team as $member) {
    // make copy of array everytime it beome empty. And work with the copy
    if (! $color1)  { $color1 = $colors; shuffle($colors); }
    ....
    echo array_pop($color1)->color;
    ...
  }

这里是你如何做到的。我对 html 标签进行了条纹处理,以使我的解决方案更易于理解。

$colors = [...]; // see your definition of the $color array
$colorCount = count($colors);
$lastColorId = null;
foreach ($team as $member)
{
    // choose a random color
    $colorId = rand(0,$colorCount-1);
    if ($lastColorId == $colorId) 
    {
        // take the next color if it's the same as the previous one
        $colorId = ($colorId + 1) % $colorCount;
    }
    $lastColorId = $colorId;
    // Get the color
    $color = $colors[$colorId]->color;
}