简体   繁体   中英

Converting associative arrays in PHP

I've been googling around and searching this forum but I haven't actually found a solution for what I need to achieve.

I'm getting an array from a db in this form

Array
(
[0] => Array
    (
        [0] => af
        [1] => Afghanistan
    )

[1] => Array
    (
        [0] => al
        [1] => Algeria
    )
)

I need it to look like this

Array
(
    [af] => Afghanistan
    [al] => Algeria
)

The db is sql server, this is the code I'm using to get the data

$sQueryCountries = "SELECT Country_Code,Country_Name FROM Countries WHERE Client_Id = '$client_id'";
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );

$rResultCountries = sqlsrv_query( $db, $sQueryCountries, $params, $options );
while ( $aRow = sqlsrv_fetch_array( $rResultCountries, SQLSRV_FETCH_NUMERIC ) )
{       
    $output[] = $aRow;      
}

Pretty basic array building in the fetch loop

while ( $aRow = sqlsrv_fetch_array( $rResultCountries, SQLSRV_FETCH_NUMERIC ) )
{       
    $output[$aRow[0]] = $aRow[1];      
}

Try this :

$res   = array();
foreach($your_array as $val){
   $res[$val[0]] = $val[1];
}

echo "<pre>";
print_r($res);

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