Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在循环重写旧值时向数组中添加值_Php_Arrays_While Loop - Fatal编程技术网

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分钟内勾选你的答案