phparraysmultidimensional-arrayresultset

Populate a 2d array from a query result and use a column value as the first level keys


I want to create this array

Array (
    [1] => Array (
        [qual] => 1
        [race] => 3
        [finish] => 1
    )
    [2] => Array (
        [qual] => 2
        [race] => 1
        [finish] => 1
    )
)

The number [1] and [2] is the driver id. This is how I get the data from the db.

$raceUitslagArray = array();
$sqlRaceUitslag = mysql_query(
    "SELECT uitslag.rijderId AS rijderId,
            combinatie.Chassis     AS chassis,
            combinatie.Motor AS motor,
            uitslag.qual AS qual,
            uitslag.race AS race,
            uitslag.finish AS finish
     FROM uitslag, combinatie
     WHERE combinatie.Rijder = uitslag.rijderId
           && uitslag.raceId = '" . $_POST['raceId'] . "'"
);
while ($inhoudRaceUitslag = mysql_fetch_array($sqlRaceUitslag)) {

the data I need in the array is:

$inhoudRaceUitslag['qual'] 
$inhoudRaceUitslag['race'] 
$inhoudRaceUitslag['finish'] 
$inhoudRaceUitslag['rijderId'] 

I think I should use:

array_push($raceUitslagArray, $inhoudRaceUitslag['rijderId']);

but I can't figure out how to get all the information in the array.


Solution

  • It's much easier than you might think. $inhoudRaceUitslag is an (associative) array, as returned by mysql_fetch_array. You can simply add it associatively to the $raceUitslagArray, like this:

    while($inhoudRaceUitslag = mysql_fetch_array($sqlRaceUitslag)) {
        $raceUitslagArray[$inhoudRaceUitslag['rijderId']] = $inhoudRaceUitslag;
    }
    

    This way you're using $inhoudRaceUitslag['rijderId'] as the key, and the entire returned row (as stored in $inhoudRaceUitslag) as value.