简体   繁体   中英

PHP Create an array from fetch array

I have a Mysql query that gives the following result as using while($row = mysql_fetch_array($res))

x | 12432

y | 232432

z | 323423

I want to take each column and put it in a new array in order to export them in a table that would look like

x | y | z

12432 | 232432 | 323423

If I fetch the same query more than once, the second row does not show up.

Can you please help?

Edit: Switch to mysqli (or PDO) as soon as you can! Plenty of reasons can be found in searchengines, so im gonna leave that to you.


You can use a nested loop to do this:

$array = array();

while($row = mysql_fetch_array($res)){
    foreach($res as $key=>$value){
        $array[$key][] = $value;
    }
}

The first round of the while will give the $array the key-names and their first value, the next litterations through the loop will only add values

That is the code that worked for me.

while($row = mysql_fetch_array($res)){

    $clients[] = $row[0];

    $stats[] = $row[1];

}

foreach ($clients as $client)
{
    echo "<td>$client</td>";
}

echo "</tr><tr>";

foreach ($stats as $stat)
{
    echo "<td>$stat</td>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM