0

我必须在循环中执行一些代码,但是每次我尝试将所有代码都放在下面的循环中时,结果集变得疯狂,给了我不真实的数据。
所以我想尝试将循环从我的代码中取出。我试过这段代码:

include 'soapproxy.php';

$proxy = SoapProxy::login("astar", "Astar2012", "48");
$xmlusers = $proxy->getUsersInGroup("vehicles", 0); 
foreach($xmlusers->user as $user) {
    if($user->id > 1){
        include 'send_data_to_db.php?user=$user->id';
    }
}

它不起作用。怎么了?

4

2 回答 2

1

好吧,如果您需要将代码分解为多个文件,那么解决问题的最佳方法是不在每次迭代中都包含该文件,而是在新文件中定义一个函数并调用该函数。(这就是上帝发明函数的原因,否则我们会在任何地方都包含文件)。使用include可以工作,但看起来像一个丑陋的黑客。

于 2013-05-21T08:38:12.243 回答
0

这样做:

include 'soapproxy.php';

$proxy = SoapProxy::login("astar", "Astar2012", "48");

$xmlusers = $proxy->getUsersInGroup("vehicles", 0); 

foreach($xmlusers->user as $user) {
    if($user->id > 1 {
        $user = $user->id; // or try $_GET['user'] = $_REQUEST['user'] = $user->id; if the included script MUST have the data inside $_GET or $_REQUEST.
        include 'send_data_to_db.php';
    }
}

Include 将简单地获取文件内容并解析它,就好像它只是在当前文件中一样。您不能将参数添加到包含调用

但正如 Rath 所说,真正的最佳解决方案是编辑 send_data_to_db.php ,并将其内容作为一个函数,以 $user 作为参数。然后你会做类似的事情:

include 'soapproxy.php';
include 'send_data_to_db.php'; // just include it once

$proxy = SoapProxy::login("astar", "Astar2012", "48");

$xmlusers = $proxy->getUsersInGroup("vehicles", 0); 

foreach($xmlusers->user as $user) {
    if($user->id > 1 {
        the_function_in_send_data_to_db.php($user->id); // call the function you created in the file multiple times
    }
}
于 2013-05-21T08:36:42.377 回答