从数组php中删除项目

时间:2014-05-15 12:33:59

标签: php arrays

我是php的新手,所以请放轻松。

我创建了一个整数数组。 1-100。我想要做的是将数组洗牌并从中删除随机数,只留下15个数字。

这是我到目前为止所做的,无法弄清楚如何删除随机数。我知道我可以使用未设置的功能,但我不确定如何在我的情况下使用它。

// Create an Array using range() function
    $element = range(1, 100);

    // Shuffling $element array randomly
    shuffle($element);

    // Set amount of number to get rid of from array
    $numbersOut = 85;

    // Remove unnecessary items from the array
    var_dump($element);

1 个答案:

答案 0 :(得分:3)

试试:

$element = range(1, 100);
shuffle($element);
$output = array_slice($element, 0, 15);

var_dump($output);

输出:

array (size=15)
  0 => int 78
  1 => int 40
  2 => int 10
  3 => int 94
  4 => int 82
  5 => int 16
  6 => int 15
  7 => int 57
  8 => int 79
  9 => int 83
  10 => int 32
  11 => int 13
  12 => int 96
  13 => int 48
  14 => int 62

或者如果您想使用$numbersOut变量:

$numbersOut = 85;
$output = array_slice($element, $numbersOut);

它会将数组从85切片到最后。请记住 - 如果数组中有90个元素,则此方法仅返回5个元素。

相关问题