Php 在循环重写旧值时向数组中添加值
这是我的代码:Php 在循环重写旧值时向数组中添加值,php,arrays,while-loop,Php,Arrays,While Loop,这是我的代码: if ( 0 < $matches->total() ) { while ( $matches->fetch() ) { ?> <?php $ma1_winner = $matches->display( 'winner' ); ?> <?php $ma1_team_1 = $matches->display( 'team_1' );
if ( 0 < $matches->total() ) {
while ( $matches->fetch() ) {
?>
<?php $ma1_winner = $matches->display( 'winner' ); ?>
<?php $ma1_team_1 = $matches->display( 'team_1' ); ?>
<?php $matches_array_1['winner'] = $ma1_winner; ?>
<?php $matches_array_1['team1'] = $ma1_team_1; ?>
<?php
} // end of while loop
} // end of if any exists
?>
<?php var_dump($matches_array_1); ?>
<?php die(); ?>
if(0<$matches->total()){
而($matches->fetch()){
?>
但它在var_dump中只输出一个winner,而不是我数据库中的15个team。如何修复它?对于每个迭代,添加一个新数组,其中包含
winner
和team
作为其键。结果将是一个包含所有值的二维数组
while ($matches->fetch() {
// Append a new array via [] = array()
// for every loop iteration
$matches_array_1[] = array(
'winner'=>$matches->display('winner'),
'team'=>$matches->display('team')
);
}
var_dump($matches_array_1);
否则,您只需在每次迭代中覆盖相同的两个键
winner
和team
。在构建数组时,您需要为每个匹配使用某种唯一的匹配标识符。例如:
<?
if ( 0 < $matches->total() )
{
while ( $matches->fetch() )
{
$matches_array_1[$matches->display('match_id')]['winner'] = $matches->display( 'winner' );
$matches_array_1[$matches->display('match_id')]['team1'] = $matches->display( 'team_1' );
} // end of while loop
} // end of if any exists
var_dump($matches_array_1);
die();
?>
对于整个代码块,您只需要/应该有一对打开/关闭的
。是的,我知道php标记不是问题。工作!很好,非常感谢。我可以问一下为什么我的代码不工作吗?@Derfder-Yours不工作,因为在每次循环迭代中,您只是设置了1的密钥赢家,团队
-维度数组到当前循环获取的值。一遍又一遍,你重写了相同的两个数组键。好的,非常感谢,我将根据弹出窗口在6分钟内勾选你的答案