Converting associative arrays in PHP

969

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;      
}
356

Answer

Solution:

Pretty basic array building in the fetch loop

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

Answer

Solution:

Try this :

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

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

People are also looking for solutions to the problem: php - showing promotion codes on pages

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.