Reputation: 1912
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:
But I want the result to be something like this:
How can I possibly do that in PHP?
Upvotes: 0
Views: 60
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
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
Reputation: 720
$array => array(pWjY=>'Value',
YA8N=>'Value',);
You can add third value with:
$array['somekey'] = 'Value';
Upvotes: 1
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