user982124
user982124

Reputation: 4600

Create an associative array using values fetched from method calls while looping

I'm trying to generate an array that will look like this:

Array ( [123 Smith St, Begora] => L1234 [55 Crumble Road, Mosmana] => L2456 [99 Jones Ave, Gestana] => L3456 )  

which will ultimately be used for a select menu on an html form.

I'm retrieving a list of records and propertyID numbers from a database as follows:

foreach($records as $record) {
    $propertyID = $record->getField('propertyID');
    $property = $record->getField('propertyAddress');  
        
    echo $propertyID.'<br>'; 
    echo $property.'<br>';              
}

which displays like this when I retrieve 3 records:

L1234 123 Smith St, Begora L2456 55 Crumble Road, Mosmana L3456 99 Jones Ave, Gestana

I just can't work out how to convert this into an Array which I can then use later on in my page for generating a select menu.

Upvotes: 0

Views: 147

Answers (2)

evuez
evuez

Reputation: 3387

Something like this:

$array = array();
foreach($records as $record) {
        $array[$record->getField('propertyAddress')] = $record->getField('propertyID');            
}

Upvotes: 1

fullybaked
fullybaked

Reputation: 4127

Just do

foreach($records as $record) {
    $propertyID = $record->getField('propertyID');
    $property = $record->getField('propertyAddress');  

    $addresses[$property] = $propertyID;
}

Upvotes: 2

Related Questions