0

I've managed to extract data from a database and assigned them into array called $NameandAge

(Peter:12, Kim:32, Paul:23)

On the other hand, I have also extracted another set of data from a different set of database and assigned them into array $StateandName

(New York:Peter, Washington:Kim, Tennessee:Paul)

What I what to achieve is to join these two sets of array into one using the Name as the key to create a table like this:

New York Peter 12,
Washington Kim 32,
Tennessee Paul 23,

I have something like below, however this takes a very long time for execution, giving me a timeout. I am looking for a better way to achieve this.

for(){       ///////////////loop array $StateandName
     for(){      ////////////loop array $NameandAge
          if($nameinfirstarr == $nameinsecondarr){
               echo .....;  ////////print out the State, Name and Age   
          }

      }
}  
Marc B
  • 356,200
  • 43
  • 426
  • 500
user1033038
  • 141
  • 3
  • 15

2 Answers2

0

No need for two loops:

foreach ($StateaandName as $state => $name) {
    $newarr[$state][$name] = $NameandAge[$name];
}

assuming that there's a 1:1 match between records in the two arrays, this will do the trick. If your arrays have different names and don't match up 1:1;, then you'd need TWO of these loops, one to work from each array in turn.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Use array_merge(). Is a PHP function than merges both arrays, overwriting values for same keys, when keys have string values, instead of numeric ones, as your case.

digitai
  • 1,870
  • 2
  • 20
  • 37