'; echo $value; echo ''; } ?>...">

Adding multiple arrays to one table

<table border="2">
<?php 
foreach($array1 as $value)
{
    echo '<tr><td>';
    echo $value;
    echo '</td></tr>';
}
?>
</table>

I have more array: array2, array3. The above code only executes the values ​​of array1, but I want all the values ​​of all arrays in the same table to be in separate columns!

array1 | array2 | array3
------------------------
       |        |
       |        |
       |        |
       |        |

I want something like this ... I tried modifying the code, but I don’t know how to do it correctly.

$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' "); 
while($rows = mysql_fetch_assoc($data)) { 
    $db_id = $rows['id']; 
    $array[] = $db_id; 
    $level = $rows['level']; 
    $array1[] = $level; 
    $exp = $rows['exp']; 
    $array2[] = $exp; 
    $pkmn_id = $rows['pkmn_id']; 
    $data1 = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' "); 
    while($rows = mysql_fetch_assoc($data1)) { 
        $poke = $rows['path']; $array3[] = $poke; 
    } 
}

The above code retrieves data from the database and adds it to different arrays!

+4
source share
2 answers

When you create your array, you do not specify the keys, so they are generated automatically. Thus, you can work with the keys for the for loop instead of using foreach in the values:

, $array3 . :

foreach($array3 as $key => $value)
{
    if (isset($array1[$key])){
        echo '<tr><td>'.$array1[$key].'</td>';
    }else{
        echo '<tr><td></td>';
    }
    if (isset($array2[$key])){
        echo '<td>'.$array2[$key].'</td>';
    }else{
        echo '<td></td>';
    }
    echo '<td>'.$array3[$key].'</td></tr>';    
}

+2

, . , , .

$i = 0;
function test($i){
    if($i < ar1.lenght && $i < ar2.lenght && $i< ar3.lenght){
        echo "<tr><td>";
        echo ar1[$i];
        echo "</td><td>";
        echo ar2[$i];
        echo "</td><td>";
        echo ar3[$i];
        echo "</td></tr>";
        $i++;
        //calls itself with an incremented $i
        test($i);
    }//else do nothing.
}

-

+1

Source: https://habr.com/ru/post/1537846/


All Articles