0

我有一些嵌套的 foreach 循环,我得到了有趣和意想不到的结果。

在下面示例代码中的第 9 行,我正在循环“$servers as $server”,在主循环的第一次迭代中,一切正常,我得到了预期的服务器列表,但对于后续迭代,我不。

然而,第 7 行的条件在“if ($synced['video_id'] == $v['id'])”时一直返回 true。

这让我问 - 我称之为 $servers 的数组 - 在第一次迭代后它是否以某种方式用完,或者我是否需要出于某种原因再次将其重置回位置 0?

    //create array of servers synced with this video, also count them for later percentage readout.
    foreach ($videos as &$v) {
        $syncArray = Array();
        $i = 0;
        foreach ($synced as $synced) {
            //find whether sync-entity pertains to this video
            if ($synced['video_id'] == $v['id']) {
                //now get name of synched server instead of id
                foreach($servers as $server) {
                    if ( $synced['server_id'] == $server['id'] ) {
                        $syncArray[$i] = $server['screenName'];
                        //if servers screen has a parent, put that in parenthesis for clarity
                        if ($server['screenParent']) {
                            $syncArray[$i] .= " (". $server['screenParent'] .")";
                        }                           
                    }
                }
                //increment for calculating percentage later
                $i++;
            }
        }
        //append the array of synced servers for this video to the videoarray
        $v['syncArray'] = $syncArray;

$servers 的 var_dump:

array(3) {
[0]=> array(4) { ["id"]=> int(9) ["userName"]=> string(20) "företag1/testskärm" ["screenName"]=> string(9) "Gate C 22" ["screenParent"]=> string(10) "Terminal 5" }
[1]=> array(4) { ["id"]=> int(15) ["userName"]=> string(15) "företag1/entre" ["screenName"]=> string(6) "Entré" ["screenParent"]=> string(14) "Avgångshallen" }
[2]=> array(4) { ["id"]=> int(17) ["userName"]=> string(14) "företag1/test" ["screenName"]=> string(4) "test" ["screenParent"]=> string(0) "" } }
4

1 回答 1

2

您的代码是为什么编程语言允许您编写函数和对象的一个​​很好的例子。

For example, how does this look like?

//create array of servers synced with this video, also count them for later percentage readout.
foreach ($videos as &$v) {
    $v['syncArray'] = get_synched_video_array_by_id($synched, $v['id']);
}

That was the first level of your nested foreach operation. Now imagine the next levels. See http://php.net/functions

The less nesting processings and conditions you have, the less complex is your code. Reducing the complexity reduces the amount of errors that can happen and how hard these errors are to track.

This should also easily solve your concrete problem of variable re-use (quoting Asad):

foreach ($synced as $synced) use different variable names for the array you are iterating over and each member

于 2012-12-29T15:30:59.387 回答