我正在 PHP 中动态构建一个简单的数组。
当我构建数组时,关键顺序是这样的(例如):
- A6
- A1
- C7
- “”(或 NULL)
- B3
然而,当我通过 引用数组时foreach()
,数组是有序的(“”,“A1”,“A6”,“B3”,“C7”)。
通过处理时如何保留数组的原始顺序foreach()
?
我假设关键顺序将是它的构建方式,但似乎要么foreach()
索引顺序,要么在途中的某个地方排序。
感谢您的帮助。
代码片段
// loop through 3rd set of query results
echo '<pre>'; /*this is here for my debugging*/
while ($row3 = mysql_fetch_array($result)) {
if (empty($teamName[$row3['team']])) {
$teamName[$row3['team']] = $row3['name'];
echo '>'.$row3['team'].'<<br />'; /*this is here for my debugging*/
}
if ($row3['id'] == $_SESSION['authenticated']['id']) $cssStyle = ' myPick';
else $cssStyle = NULL;
$html[$row3['team']] .= '<li class="bcPicks' . $cssStyle . '">';
$html[$row3['team']] .= '<span class="bcPicks_displayName">' . $row3['displayName'] . '</span>';
if (!empty($row3['team'])) {
$html[$row3['team']] .= ' in ';
$html[$row3['team']] .= '<span class="bcPicks_paddingA">' . $row3['games'] . '</span>';
}
else {
$html[$row3['team']] .= '<span class="bcPicks_paddingB"></span>';
}
if ($row3['points'] < 0) $cssStyle = 'negative';
else $cssStyle = 'positive';
$html[$row3['team']] .= '(<span class="bcPicks_' . $cssStyle . '">' . signedNumber($row3['points']) . ' points</span>)';
$html[$row3['team']] .= '</li>';
} // end while() loop through 3rd set of query results
// free-up memory
mysql_free_result($result);
print_r($html);echo '</pre>';var_dump($html);exit; /*this is here for my debugging*/
foreach ($html as $key => $value) {...}
我可以告诉你,我的print_r()
和var_dump()
两者都表明,产生的顺序foreach()
不是它的构建方式。
这是数组的转储
>E5<
>E4<
><
Array
(
[] =>
name1(0 points)
[E4] =>
name2 in 5(-2 points)
name3 in 6(-2 points)
name4 in 7(-2 points)
name5 in 7(-2 points)
name6 in 7(-2 points)
name7 in 7(-2 points)
name7 in 7(-2 points)
[E5] =>
name9 in 4(+8 points)
name10 in 7(+8 points)
name11 in 7(+8 points)
)
array(3) { [""]=> string(158) "
name1(0 points)
" ["E4"]=> string(1156) "
name2 in 5(-2 points)
name3 in 6(-2 points)
name4 in 7(-2 points)
name5 in 7(-2 points)
name6 in 7(-2 points)
name7 in 7(-2 points)
name8 in 7(-2 points)
" ["E5"]=> string(495) "
name9 in 4(+8 points)
name10 in 7(+8 points)
name11 in 7(+8 points)
" }
上面你可以看到它是 'E5'、'E4' 和 NULL 构建的,但是数组转储以 NULL、'E4' 和 'E5' 的顺序显示它