[英]How to create an associative array from more than two columns fetched from a sql query in PHP?
I'm trying to fill an associative array with values from a fetched sql query, I've used this before for just two columns: 我正在尝试使用来自获取的sql查询的值填充关联数组,之前我仅将其用于两列:
while($row = odbc_fetch_array($res1)){
$key_words[utf8_encode($row['word'])] = utf8_encode($row['replace']);
}
Ouputs: 。OUPUTS:
Array (
[à] => a
[á] => a
[â] => a
[ã] => a
[ä] => a
[ç] => c
[é] => e
[è] => e
[ê] => e
)
But now I need for more than two columns. 但是现在我需要两个以上的列。 something like this: 像这样的东西:
$array = array( subject => key => group subject => key => group )
Is it possible ? 可能吗 ?
EDIT 2 编辑2
This code: 这段代码:
while($row = odbc_fetch_array($res)){
$replace[] = $row;
}
outputs this result: 输出结果:
Array (
[0] => Array (
[ID] => 1
[mot] => �
[remplace] => a
[Type] => lettre
)
[1] => Array (
[ID] => 2
[mot] => �
[remplace] => a
[Type] => lettre
)
[2] => Array (
[ID] => 3
[mot] => �
[remplace] => a
[Type] => lettre
)
)
I want the same result but not with all the columns just 3. 我想要相同的结果,但不希望所有列都只有3个。
EXAMPLE: 例:
Array (
[0] => Array (
[mot] => �
[remplace] => a
[Type] => lettre
)
[1] => Array (
[mot] => �
[remplace] => a
[Type] => lettre
)
[2] => Array (
[mot] => �
[remplace] => a
[Type] => lettre
)
)
There are multiple ways you can get that result. 您可以通过多种方式获得该结果。
Since you seem to be fetching the data from a database, the best would be if you just selected the columns you want. 由于您似乎正在从数据库中获取数据,因此最好的方法是仅选择所需的列。
If you have this today: 如果今天有这个:
SELECT * FROM ...
Change it to: 更改为:
SELECT mot, remplace, Type FROM ...
Now $row
will just contain those three values and you can use the code you have: 现在$row
将只包含这三个值,您可以使用已有的代码:
while($row = odbc_fetch_array($res)){
$replace[] = $row;
}
If you, for what ever reason, don't want to limit the columns you fetch, you can just use the columns you want using PHP inside the loop: 如果出于某种原因而不想限制获取的列,则可以在循环内使用需要使用PHP的列:
while($row = odbc_fetch_array($res)){
$replace[] = [
'mot' => $row['mot'],
'remplace' => $row['remplace'],
'Type' => $row['Type'],
];
}
Both the above solutions should give you the result you want. 以上两种解决方案都应该为您提供所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.