我有一些嵌套的 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) "" } }