2

In PHP I am going to edit some entity let say a project named: ABC this projects belongs to many countries while adding this project I used <select multiple="multiple"> and store all selected countries in a projectCountries table. Now when I start editing this project so I use same logic with a little change:

  1. populate all countries from countries table
  2. fetch all countries from projectCountries table which are associate with projectId

and I got two arrays:

Array ( 
    [0] => Array ( [countryId] => 1 [countryName] => Pakistan ) 
    [1] => Array ( [countryId] => 2 [countryName] => China ) 
) 

output from step-1

and

Array ( 
    [0] => Array ( [pcId] => 1 [countryId] => 1 [projectId] => 1 ) 
    [1] => Array ( [pcId] => 2 [countryId] => 2 [projectId] => 1 ) 
)

output from step-2

but I am confused how to show that country named China was already associated with the project (already selected in <select multiple="multiple">)

because to create <select multiple="multiple"> I used foreach loop. Now I could not guess how to compare two arrays in foreach loop so that I set selected="selected" in <option>.

2 Answers 2

3

Iterate over all countries and check if that country exists on the projectCountries output array.

Something like this:

$pc_list = array();
foreach($project_countries as $pc) {
    $pc_list[] = $pc['countryId'];  
}

foreach($countries as &$country) {
    if(in_array($country['countryId'], $pc_list)) {
        $country['selected'] = TRUE;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Option 1: Run the foreach loop for step1. In every iteration you could iterate through the second array and check if there is a country with the current id (from the first loop).

Option 2: Change your SQL-Query to something like that (with a join for example):

CountryId CountryName ProjectId
1 Pakistan 1
2 China 1
3 Germany null

Comments

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.