crush123 Posted August 25, 2010 Share Posted August 25, 2010 i have 2 associative arrays, similar to below..Array ( [5] => A [11] => B [16] => C [4] => D )Array ( [11] => Apples [5] => Bananas [4] => Oranges [16] => Plums )i want to process them to get the following result, which is essentially the key order from the first array, with the values from the secondArray ( [5] => Bananas [11] => Apples [16] => Plums [4] => Oranges )i have been playing withthe various array functions for a few hours now, but can't get the result I am after.Very grateful for a few pointers.thanks Link to comment Share on other sites More sharing options...
boen_robot Posted August 25, 2010 Share Posted August 25, 2010 You could use array_keys() and array_values() to get the keys and values from the respective arrays, then loop over one of the arrays to form a third array.Here's an example, assuming your original arrays are called $arr1 and $arr2: $keysArr = array_keys($arr1);$valsArr = array_values($arr2);$resultArr = array();foreach($keysArr as $ind => $key) {$resultArr[$key] = $valsArr[$ind];} This is somewhat a memory wasting way to do it (you need the memory for each array... doubled... plus more for the resulting array), but it works. Link to comment Share on other sites More sharing options...
crush123 Posted August 25, 2010 Author Share Posted August 25, 2010 Great job.that looks like a good solution, I'll give it a go Link to comment Share on other sites More sharing options...
wirehopper Posted August 26, 2010 Share Posted August 26, 2010 http://www.php.net/manual/en/function.arra...tersect-key.php<?php$array1 = array(5=>'A',11=>'B',16=>'C',4=>'D');$array2 = array(11=>'Apples',5=>'Bananas',4=>'Oranges',16=>'Plums');var_dump(array_intersect_key($array2, $array1));?> Output: array(4) { [11]=> string(6) "Apples" [5]=> string(7) "Bananas" [4]=> string(7) "Oranges" [16]=> string(5) "Plums"} Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.