PHP中的二维关联数组

时间:2023-01-13 12:48:11

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:

在我的代码中,我从sql db获取数据(三列),我想将行存储在关联的PHP数组中。该数组必须是多维的,因为我想使用数据库中的行id作为键,以便我可以获取如下值:

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

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

I've tried using the following code but it doesn't work:

我尝试使用以下代码,但它不起作用:

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

Also, how should I reference the key if it is taken from a variable? What I want to do is:

另外,如果从变量中获取密钥,我该如何引用密钥呢?我想做的是:

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

Will this work?

这会有用吗?

1 个解决方案

#1


This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):

这应该这样做,假设row [0]的内容是唯一标识符(否则你可以覆盖一行):

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

You need to put quotes around the array keys, and you were creating an array of array of arrays.

您需要在数组键周围添加引号,并且您正在创建一个数组数组的数组。

Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:

另请注意,您可以使用mysql_fetch_assoc而不是mysql_fetch_row,这将为您提供数组键作为列名,这将使这更容易/更清洁:

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

After you do this, the code you described would work.

执行此操作后,您描述的代码将起作用。

#1


This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):

这应该这样做,假设row [0]的内容是唯一标识符(否则你可以覆盖一行):

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

You need to put quotes around the array keys, and you were creating an array of array of arrays.

您需要在数组键周围添加引号,并且您正在创建一个数组数组的数组。

Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:

另请注意,您可以使用mysql_fetch_assoc而不是mysql_fetch_row,这将为您提供数组键作为列名,这将使这更容易/更清洁:

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

After you do this, the code you described would work.

执行此操作后,您描述的代码将起作用。