将动态参数传递到函数中


Passing dynamic parameters into a function

假设我有一个名为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"

我可以使用选择结构,但该解决方案存在严重缺陷,因为一台服务器将始终优先于其他服务器。就像如果服务器 1 详细信息为空$result,请移动到服务器 2,这真的不是我想要的。

我正在考虑数组,但我不确定它将如何完成,因为我需要随机选择一组详细信息,如果一组失败,请尝试另一组,直到没有服务器或$result有一个值。

从@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
}

我想你正在寻找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()返回的密钥,继续循环直到连接,或者失败