猿问

如何从数组中输出不同的值

我的代码有问题。我想做的是在数组被调用时从数组中删除一个项目,这意味着我希望每个输出都不同。我想用它来旋转代理,阵列中有超过 150 个代理。这是我的代码示例。



for ( $i = 1; $i < 2; $i++ )

{

  // If the array_history is empty, re-populate it.

  if (empty($array_history))

    $array_history = $array;


  // Select a random key.

  $key = array_rand($array_history, 1);


  // Save the record in $selected.

  $selected = $array_history[$key];


  // Remove the key/pair from the array.

  unset($array_history[$key]);


  // Echo the selected value.

  echo $selected; 

}

我该怎么做,或者 for 循环不适合这个?提前致谢。


largeQ
浏览 134回答 3
3回答

PIPIONE

您想要做的是将访问分散到 150 个代理上。在这种情况下,没有必要随机进行。你可以通过数组。<?php&nbsp;$array = [0, 1, 2, 3, 4, 5, 6];for ( $i = 1; $i < 20; $i++ ){&nbsp; &nbsp; echo getNext($array) . '<br>';}function getNext (&$array) {&nbsp; $e = next($array); // Every time next element is selected. Each output is different.&nbsp; if ($e)&nbsp; &nbsp; return $e;&nbsp; else&nbsp;&nbsp; &nbsp; return reset($array);}?>

鸿蒙传说

这似乎是生成器的一个很好的应用程序。这一个采用一组代理地址并以随机顺序在数组上循环,每次重新开始循环时都会对数组进行洗牌。function get_proxy($proxies) {&nbsp; &nbsp; $i = 0;&nbsp; &nbsp; $len = count($proxies);&nbsp; &nbsp; while (true) {&nbsp; &nbsp; &nbsp; &nbsp; if ($i == 0) shuffle($proxies);&nbsp; &nbsp; &nbsp; &nbsp; yield $proxies[$i];&nbsp; &nbsp; &nbsp; &nbsp; $i = ($i + 1) % $len;&nbsp; &nbsp; }}要使用它,您将执行以下操作:$proxies = array('10.0.0.4', '192.168.0.1', '10.1.0.1');$i = 0;foreach (get_proxy($proxies) as $proxy) {&nbsp; &nbsp; echo "$proxy\n";&nbsp; &nbsp; $i++;&nbsp; &nbsp; // stop otherwise infinite loop&nbsp; &nbsp; if ($i == 9) break;}请注意,由于生成器中有一个无限循环,因此外部foreach循环也将是无限的,因此需要一种方法来打破(在这种情况下我使用了一个简单的计数器)。上述代码的示例输出:10.1.0.110.0.0.4192.168.0.1192.168.0.110.1.0.110.0.0.410.1.0.1192.168.0.110.0.0.4如果生成器不适合您的代码结构,您可以使用带有静态变量的函数在每次调用时返回一个新代理:$proxies = array('10.0.0.4', '192.168.0.1', '10.1.0.1');function get_proxy($proxies) {&nbsp; &nbsp; static $i = 0, $keys;&nbsp; &nbsp; if (!isset($keys)) $keys = array_keys($proxies);&nbsp; &nbsp; if ($i == 0) shuffle($keys);&nbsp; &nbsp; $proxy = $proxies[$keys[$i]];&nbsp; &nbsp; $i = ($i + 1) % count($keys);&nbsp; &nbsp; return $proxy;}for ($i= 0; $i < 9; $i++) {&nbsp; &nbsp; echo get_proxy($proxies) . "\n";}此代码的示例输出:10.1.0.110.0.0.4192.168.0.1192.168.0.110.1.0.110.0.0.410.0.0.4192.168.0.110.1.0.1

函数式编程

当您在 php 中定义一个数组时,例如<?php$alphabet = array(a, b, c)?>&nbsp;您试图在数组中查找元素。元素列表始终从 0 开始计数。因此,调用单个元素从 0 开始从左到右计数。<?php#aecho $alphabet[0];#becho $alphabet[1];#cecho $alphabet[2];&nbsp;?>&nbsp;上面的部分应该产生 abc 的结果,因为没有中断。For 循环对于遍历整个数组并运行检查、错误分析甚至数学作为示例非常方便。
随时随地看视频慕课网APP
我要回答