假设我有一个名为ssh_connect
的函数,它将服务器SSH设置作为参数。现在我有多个服务器,我想随机选择其中一个并将它们作为参数输入到函数中。如果是$ result使用一组参数时为空,另一组必须使用
$result=ssh_connect($ip, $user, $pass, $port,$command)
假设我有以下详细信息
//Server 1
$ip="123.456.78.901";
$user="root"
$pass="mypassishere"
$port = "22"
//Server 2
$ip="225.456.98.901"
$user="root"
$pass="mypassishere"
$port = "22"
我可以使用选择结构但是该解决方案存在严重缺陷,因为一个服务器将始终优先于其他服务器。如果$result
为空,服务器1的详细信息,移动到服务器2,这实际上是不是我想要的。
我正在考虑数组,但我不确定它是如何完成的,因为我需要随机选择一组细节,如果一组失败,请尝试另一组,直到没有服务器或$ result有值。< / p>
答案 0 :(得分:1)
我认为你正在寻找aray_rand,php网站状态
Picks one or more random entries out of an array,
and returns the key (or keys) of the random entries.
如果设置失败,请取消设置array_rand()
返回的密钥,保持循环直至连接或失败
答案 1 :(得分:1)
继续@gwillie的回答,这是一个例子:
<?php
$a = array(
array('host'=>'host1','user'=>'user1','pwd'=>'pwd1'),
array('host'=>'host2','user'=>'user2','pwd'=>'pwd2'),
array('host'=>'host3','user'=>'user3','pwd'=>'pwd3'),
array('host'=>'host4','user'=>'user4','pwd'=>'pwd4'),
array('host'=>'host5','user'=>'user5','pwd'=>'pwd5'),
);
$connect = false;
while (!$connect) {
$srvIndex = array_rand($a);
$host = $a[$srvIndex];
$connect = my_connect_function($host); //Return true on success, false on error
}