循环获取另一个php变量,通过引用将多个变量传递给foreach循环(php)

场景/问题隔离

:假设我的程序使用多个变量。在程序开始时,我希望通过一个代码很少的通用函数同时操作许多变量,然后在流程的后面,在特定函数中只使用一些独特的变量。

问题

:如何通过引用foreach循环传递多个变量?或者是否有更好的/可选的方法来循环使用多个确定的变量?

与主题相关的帖子

但没有解决我的问题:

背景(相关人员):

我有一个使用getopts的命令行程序

http://hash-bang.net/2008/12/missing-php-functions-getopts/

为了得到各种各样的参数,我得到了大约20个变量。我想运行所有变量,这些变量包含文件路径(大约10个),一次通过“常规”函数reduceHierarchyDots()(而不是调用函数10次)。

/// The "general" function:

function reduceHierarchyDots ($file) {

while (preg_match('|./\.{2}/|', $file)) { $file = preg_replace('|/([^/]+)/\.{2}/|', '/', $file, 1); }

$file = preg_replace('|(/(\./)+)|', '/', $file);

$file = preg_replace('|^(\./)+|', '', $file);

return $file;

}

function reduceHierarchyDotsRef (&$file) {

while (preg_match('|./\.{2}/|', $file)) { $file = preg_replace('|/([^/]+)/\.{2}/|', '/', $file, 1); }

$file = preg_replace('|(/(\./)+)|', '/', $file);

$file = preg_replace('|^(\./)+|', '', $file);

}

/// The "many" variables:

$x = "something";

$y = 123;

$y = array ("a", "B", 3);

$a = "/Users/jondoe/Desktop/source/0.txt";

$b = "/Users/jondoe/Desktop/source/../1.txt";

$c = "/Users/jondoe/Desktop/source/../../2.txt";

$arrOne = array (

"v1" => "/some/thing/../1.pdf",

"v2" => "/some/thing/../../2.pdf",

"v3" => "/some/thing/../../../3.pdf"

);

$arrTwo = array (

"./1.doc",

"/so.me/.thing/ends./././2.doc",

"./././3.doc"

);

/// At the beginning I want to run multiple determined variables through a "general" function:

/// Debugging: Variables BEFORE the manipulation:

echo("BEFORE:\n"); var_dump($b, $arrOne["v2"], $arrTwo[2]); echo("\n");

/// Method works, but is long! (1 line/statement per function call)

reduceHierarchyDotsRef($b);

reduceHierarchyDotsRef($arrOne["v2"]);

reduceHierarchyDotsRef($arrTwo[2]);

/// Hence, I'd like to pass all variables by reference at once to a foreach loop:

These cause: Parse error: syntax error, unexpected '&':

// foreach ( array($b, $arrOne["v2"], $arrTwo[2] ) as &$file) { $file = reduceHierarchyDots($file); }

// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as &$file) { $file = reduceHierarchyDotsRef($file); }

These have no effect on the intended variables:

// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as $file) { $file = reduceHierarchyDots($file); }

// foreach (array(&$b, &$arrOne["v2"], &$arrTwo[2] ) as $file) { $file = reduceHierarchyDotsRef($file); }

/// Debugging: Variables AFTER the manipulation:

echo("AFTER:\n"); var_dump($b, $arrOne["v2"], $arrTwo[2]);

/// After the "general" function ran over various variables, the more specific actions happen: ...

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值