简体   繁体   中英

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:

while($row = odbc_fetch_array($res1)){
    $key_words[utf8_encode($row['word'])] = utf8_encode($row['replace']);
}

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
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.

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.

Using SQL

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:

while($row = odbc_fetch_array($res)){
    $replace[] = $row;
}

Using PHP

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:

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.

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