0

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?

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

You can add third value with:

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

Comments

1

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.')' ;
}

Comments

1

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.')';

1 Comment

This wont result in the output that he wants, he will get nested arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.