As usual, late to the party... :-) Someone may find it useful.
Here is a tested version (PHP 5.3.18), that uses the original data structures. It should be faster for large input arrays because it converts the 'list of 'place', colour' into an array with a key of 'place' that has a value of 'colour'. i.e. you can look up the colour for a 'place' directly. The reqired 'colour' can then be 'looked up' directly given the 'place'.
The code is commented.
<?php // https://stackoverflow.com/questions/26689542/php-match-keys-and-copy-values-to-new-array
$places = array ('0' => 'London', '1' => 'New York', '2' => 'Paris', '3' => 'Sydney', '4' => 'Bangkok');
$colours = array ( '0' => array ( '0' => 'Madrid', '1' => 'Blue' ), '1' => array ( '0' => 'London', '1' => 'Yellow' ) , '2' => array ( '0' => 'Hong Kong' ,'1' => 'Orange' ) , '3' => array ( '0' => 'Paris', '1' => 'Purple' ), '4' => array ( '0' => 'Sydney', '1' => 'Pink' ));
$result = array();
foreach ($places as $placeName) {
$result[] = array( $placeName, placesToColourLookup($placeName));
}
// show output places with colours
var_dump($result);
// end of program
/*
* @param string Place name
* @return string Coulour or empty string if not found
*/
function placesToColourLookup($placeName)
{
global $colours;
static $colourLookup = null; // only convert the 'place -> colour array once!
// convert the supplied place -> colour array to an array keyed by 'placeName'.
// for fast lookup after the first time...
if (is_null($colourLookup)) {
foreach ($colours as $placeToColour) { // this is an array( place, colour)
$colourLookup[current($placeToColour)] = next($placeToColour);
}
// var_dump($colourLookup);
}
// now return the approprate colour...
if (isset($colourLookup[$placeName])) {
return $colourLookup[$placeName];
}
return '';
}
foreach($places as $key => $value)should point you in the right direction.$result = Array ( [0] => Array ( ['place'] => London ['colour'] => Yellow) )