I want to expand my city array with post code value. If the city_postcode array contain city array name record then push postcode value into city array. That’s what i want to achive somehow.
city array:
Array ( [0] => Array ( [id] => 1 [city] => Budapest [population] => 1700000 ) [1] => Array ( [id] => 2 [city] => Szeged [population] => 160000 ) )
city_postcode array:
Array ( [0] => Array ( [name] => Budapest [post_code] => 12345 ) [1] => Array ( [name] => Szeged [post_code] => 33356 ) )
The result I want:
Array ( [0] => Array ( [id] => 1 [city] => Budapest [population] => 1700000 [post_code] => 12345 ) [1] => Array ( [id] => 2 [city] => Szeged [population] => 160000 [post_code] => 33356 ) )
Advertisement
Answer
If you can rely on the cities and post codes to be equal in length and sorted, you could just do something like this:
<?php $cities = array( array("id"=>1,"city"=>"Budapest","Population"=>"1700000"), array("id"=>2,"city"=>"Szeged","Population"=>"160000") ); $cityPostCode = array( array("name"=>"Budapest","post_code"=>12345), array("name"=>"Szeged","post_code"=>33356) ); for($i = 0; $i < count($cities); $i++){ $cities[$i]['post_code'] = $cityPostCode[$i]['post_code']; } print_r($cities);
Other wise you could do something more dyanmic like:
function _parsePostCode($targetName,$targetArr){ foreach($targetArr as $el){ if($el['name'] == $targetName){ return $el['post_code']; } } return false; } for($i = 0; $i < count($cities); $i++){ $cities[$i]['post_code'] = _parsePostCode($cities[$i]['city'],$cityPostCode); } print_r($cities);