This function could be better

    Date: 07/12/06 (PHP Community)    Keywords: php, database

    PHP -

    I've got this function. I know there's a better way to get the keys and values of arrays, but I can't think of it. Do you have any ideas?

    EDIT >>>

    Basically, the function takes two arrays in, and looks for keys in array2 (minus a frm_ prepending for form submission) that match keys in array1. I take the key from array1 and put the value of array2 in the output array.

    array2 is the $_SESSION array. array1 is an array of values from a database entry. Fields from a form are saved in the $_SESSION array so I can fill them in if there was an error on insertion.

    <<<


    function joinData($array1, $array2) {
    	$len1 = count($array1); //length of array 1 - speeds up loops
    	$len2 = count($array2); //length of array 2
    
    	$keys1 = array_keys($array1); //keys of array1
    	$vals1 = array_values($array1); //values of array 1
    
    	$keys2 = array_keys($array2); //keys of array2
    	$vals2 = array_values($array2); //values of array 2
    
    	$output = array(); //what we send out
    
    	for($i=0;$i<$len1;$i++) { //foreach element in array 1
    		for($j=0;$j<$len2;$j++) { //search each element in array 2
    			if( ($keys1[$i] == ereg_replace("frm_","",$keys2[$j])) ) { //until we find a key that matches after stripping frm_
    				$output[$keys1[$i]] = $vals2[$j]; // overwrite the value in array1; array2 takes precidence
    				break; // go to next element in array 1 - speeds up process (function is O(n log n), instead of O(n^2))
    			}
    		}
    	}
    
    	return $output; //send back the new values
    }

    Source: http://community.livejournal.com/php/469583.html

« Dreamhost and include() || Here's one for ya.. »


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home