避免在array_rand循环上重复输出

时间:2018-04-04 23:01:11

标签: php arrays loops

我试图在一个循环中循环遍历一个数组最多次,但是我想弄清楚如何让它不输出相同的两次。

以下是代码的关键所在,删除了所有多余的代码。

以前,当我查看此代码时,我已经注释了unset()。我不认为它正在做它应该做的事情,我真的想不出一种方法来阻止它而不向个别数组添加id

我构建了这个虚拟数组:

$array = array(
    array(
        'title'     =>  'Bill',
        'url'       =>  'example.com/?u=1',
        'img'       =>  'image1.jpg'
    ),
    array(
        'title'     =>  'Frank',
        'url'       =>  'example.com/?u=2',
        'img'       =>  'image1.jpg'
    ),
    array(
        'title'     =>  'Jill',
        'url'       =>  'example.com/?u=3',
        'img'       =>  'image1.jpg'
    )
    ...
);

我有output页面:

$a = 0;
$m = 2; // output max two set via $max

foreach( $users as $user ) {

    $a++;
    // unset( $users[$random_out] );

    if( $a < $m ) {

        $random_out = array_rand( $users );
        $user_title = $users[$random_out]['title'];
        $user_url    = $users[$random_out]['url'];
        $user_img    = $users[$random_outid]['img'];

        echo '<a href="' . $user_url . '">';
            echo '<img src="' . $user_img . '">';
            echo $user_title;
        echo '</a>';
    }

}

3 个答案:

答案 0 :(得分:1)

您可以使用array_rand的第二个参数($num)来获得结果。如果指定了$num,则array_rand将返回一组随机密钥。

foreach (array_rand($users, $m) as $random_out);
    $user_title  = $users[$random_out]['title'];
    $user_url    = $users[$random_out]['url'];
    $user_img    = $users[$random_outid]['img'];

    echo '<a href="' . $user_url . '">';
    echo '<img src="' . $user_img . '">';
    echo $user_title;
    echo '</a>';
}

答案 1 :(得分:0)

正如@Sammitch所指出的,shuffle + array_slice是一个更简单的解决方案。如果您不希望对原始数组进行混洗,请复制它。

// Shuffle the Array
shuffle( $users );
// Loop over the first two items from the array
foreach( array_slice( $users, 0, 2 ) as $user )
{
  echo '<a href="' . $user['url'] . '">';
  echo '<img src="' . $user['img'] . '">';
  echo $user['title'];
  echo '</a>';
}

此功能将从阵列池中选择$limit个唯一项目

$array = array('cat','dog','hamster','elephant','otter');

function random_unique_items_from_array( $array, $limit = 1 )
{
  $history = array();
  $result = array();
  while( count( $result ) < $limit and count( $history ) < count( $array ) )
  {
    if( in_array( $randKey = array_rand( $array ), $history ) === false )
    {
      $history[] = $randKey;
      $result[ $randKey ] = $array[ $randKey ];
    }
  }
  return $result;
}

var_dump( random_unique_items_from_array( $array, 2 ) );
var_dump( random_unique_items_from_array( $array, 5 ) );
var_dump( random_unique_items_from_array( $array, 500 ) );

所以现在不要在循环中保持跟踪,而是执行此操作

foreach( random_unique_items_from_array( $users, 2 ) as $user )
{
  echo '<a href="' . $user['url'] . '">';
  echo '<img src="' . $user['img'] . '">';
  echo $user['title'];
  echo '</a>';
}

答案 2 :(得分:0)

如果你只想要独特的用户,你可以做这样的事情;

<?php

$array = array(
    array(
        'title'     =>  'Bill',
        'url'       =>  'example.com/?u=1',
        'img'       =>  'image1.jpg'
    ),
    array(
        'title'     =>  'Frank',
        'url'       =>  'example.com/?u=2',
        'img'       =>  'image1.jpg'
    ),
    array(
        'title'     =>  'Jill',
        'url'       =>  'example.com/?u=3',
        'img'       =>  'image1.jpg'
    )
);

//set the number of random users you want
$totalNumberOfRandomUsers = 2;

// loop over the number of random users you want
for($i = 1; $i <= $totalNumberOfRandomUsers; $i++) {
    // get a random number between 0 and the count of the array - 1 
    // as arrays are zero indexed
    $rand = rand(0,count($array)-1);
    // get the nth index of the array and assign it to a users array
    $users[] = $array[$rand];
    // unset the index you've just added and 'reset' the array
    // so that there are no missing indexes
    unset($array[$rand]);
    $array = array_values($array);
}

// die and dump the users array.
die(var_dump($users));