Question

<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 values of array1 but I want all the values of all array in the same table in separate columns!

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

I want something like this... I tried modifying the code but no idea 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 fetches data from database and adds it to different arrays!

Was it helpful?

Solution

When you create your array, you don't specify keys, so they are generated automaticaly. So you can work on keys for your for loop instead of using a foreach in values:

We can see in your code that $array3 is longuer than the others. So we will base on it:

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>';    
}

It should work

OTHER TIPS

try making a function that calls itself in the end. not sure if I got the syntax right here, but this should work.

$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.
}

--edit forgot some tags

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top