如何在PHP中使用两个函数中的一个数组


How to use one array in two functions in PHP?

我有一个包含以下内容的数组:

 $array_test = array ("User1"=>"Test1",
                      "User2"=>"Test2");

函数中的第一列应为$uservalue,第二列为$testvalue。当我在函数中的第一个函数循环中使用单列数组时,它就起了作用。

我想在下面的两个函数中使用这个数组。数组的第一列应该用作$uservalue。

function do_show(array $options) {
    global $showresult, $master;
    $cn = $uservalue;
    $config = $options["config"]->value;
    // an empty show tag
    $show = new SimpleXMLElement("<show/>");
    // add the user tag
    $user = $show->addChild("user");
    // add the "cn" attribute
    $user->addAttribute("cn", $cn);
    if ($config)
        $user->addAttribute("config", "true");
    print "cmd: " . htmlspecialchars($show->asXML()) . "'n";
    // do it
    $showresult = $masterPBX->Admin($show->asXML());
    print "result: " . htmlspecialchars($showresult) . "'n";
    }

第二个函数,我想使用数组的第二列作为$testvalue:的值

function do_modify(array $options) {
    global $showresult, $master;
    $mod = $testvalue;
    $modify = new SimpleXMLElement("$showresult");
    $user = $modify->user;
    $path = explode("/device/hw/", $mod);
    $srch = $user;
    $nsegments = count($path);
    $i = 1;
    foreach ($path as $p) {
        if ($i == $nsegments) {
            // last part, the modification
            list($attr, $value) = explode("=", $p);
            $srch[$attr] = $value;
        } else {
            $srch = $srch->$p;
        }
        $i++;
    }
    // wrap the modified user tag in to a <modify> tag
    $modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
    print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "'n";
    $result = $master->Admin($cmd);
    print "result: " . htmlspecialchars($result);
}

我该如何存档?我在软件的wiki中发现了这两个功能,我想实现这个。。。因此,我知道使用全局变量不是一个好的选择。

您可以使用以下代码将数组拆分为两个数组,并将适当的数组传递给相关函数。

$array_test = array ("User1"=>"Test1",
                      "User2"=>"Test2");
$array_users = array_keys($array_test);
$array_tests = array_values($array_test);

以下是有关array_values和array_keys函数的详细信息的链接。

将数组作为函数参数传递给两个函数。。。或者使阵列全局化。如果要更改原始数组(在函数内部进行的数组更改在函数外部可见),则通过引用传递。