Two-dimensional associative array in PHP

In my code, I get data (three columns) from sql db, and I want to store the rows in an associative PHP array. The array must be multidimensional because I want to use the row id from the database as the key so that I can get the following values:

$ products ["f84jjg"] ["name"]

$ products ["245"] ["code"]

I tried using the following code, but it does not work:

while ($row = mysql_fetch_row($sqlresult))
{
    $products = array($row[0] => array(
            name => $row[1], 
            code => $row[2]
        )
    );
}

Also, how should I refer to a key if it is taken from a variable? I want to do this:

$productName = $products[$thisProd]["name"];

Will this work?

+3
source share
1 answer

, , row[0] ( ):

while($row = mysql_fetch_row($sqlresult)) {
    $products[$row[0]] = array(
        'name' => $row[1], 
        'code' => $row[2]
    );
}

, .

, mysql_fetch_row mysql_fetch_assoc, , /:

while($row = mysql_fetch_assoc($sqlresult)) {
    $products[$row['myidcolumn']] = $row;
}

, , .

+8

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


All Articles