Jay Marz
Jay Marz

Reputation: 1912

How to assign series of values to an array in php?

I am using foreach loop to assign values to an array.

$route_selection;
    foreach ($routes as $route) {
        $from_state = $route->fromState->name;
        $to_state = $route->toState->name;
        $from_country = $route->fromCountry->name;
        $to_country = $route->tocountry->name; 
        $route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];
    }

Sure enough, it will have a result to something like this: enter image description here

But I want the result to be something like this: enter image description here

How can I possibly do that in PHP?

Upvotes: 0

Views: 60

Answers (4)

Satya
Satya

Reputation: 8881

change this line

$route_selection[] = [$route->hash_id => 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')'];

to

$route_selection[$route->hash_id] =  'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')';

Upvotes: 1

Amit Joshi
Amit Joshi

Reputation: 1354

Do this:

$route_selection;
foreach ($routes as $route) {
    $from_state = $route->fromState->name;
    $to_state = $route->toState->name;
    $from_country = $route->fromCountry->name;
    $to_country = $route->tocountry->name; 
    $route_selection[$route->hash_id] =  'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')' ;
}

Upvotes: 1

trenccan
trenccan

Reputation: 720

$array => array(pWjY=>'Value',
                YA8N=>'Value',);

You can add third value with:

$array['somekey'] = 'Value';

Upvotes: 1

DrRoach
DrRoach

Reputation: 1356

Change your array assigning line to:

$route_selection[$route->hash_id] = 'From: '.$from_state.' ('.$from_country.') To: '.$to_state.' ('.$to_country.')';

As long as each hash_id is unique, this will create a new array element for each route.

Upvotes: 4

Related Questions