pornophobic Posted September 9, 2010 Share Posted September 9, 2010 What I'm trying to do is take two arrays and combine them using array_combine. After they are combined I want to take each key and value pair and use them in a string to build a MySQL query. See below for some pseudo-code =D <?php $fields = array('first_name', 'last_name'); //the fields that will be set with an UPDATE query. $newvals = array('Joe', 'Blow');//The values that will go into $fields $arr = array_combine($fields, $newvals);//Each value now has a key of the field it will update. /** This is where I want to return my SET string with something like 'SET ' . $arr['first_name'] ' = ' . $arr['first_name_value'] ', etc etc. */ There it is, I suppose. Are there any easier ways of doing what I'm trying to accomplish, that is, am I on the right track or just making things harder for myself? Both arrays will have dynamic values throughout my application, so I need to be able to get both each field and value for each query. Any links to some constructs, etc, etc? That's all I really need and I can post the solution when I've figured it out. Quote Link to comment Share on other sites More sharing options...
pornophobic Posted September 9, 2010 Author Share Posted September 9, 2010 Got it. I've used a combination of substr, key, current, and next. See how I implemented it below: function set($fields, $newvals) { if ( is_array($fields) && is_array($newvals) ) { if ( count(array_diff_key($fields, $newvals)) !== 0 ) { Error::toss('query', 1, 'Array lengths must match in ' . __METHOD__); //Method in some other class I've written to toss an error if arrays aren't same length. } else { $arr = array_combine($fields, $newvals); //combine the two arrays $q = ''; //So there isn't a warning about an undeclared variable. while ( $field = current($arr) ) { $q .= key($arr) . ' = \'' . current($arr) . '\', '; //Prints out $field = '$value', next($arr); //Move to next element in array. } $q = substr($q, 0, -2); //After the string is completed, remove 2 chars from the end (extra ", ") } //going to throw in what to do if neither are arrays. } $this->qbuild .= 'SET ' . $q; //Return my SET query with the values I need, } Hope that helps someone. Quote Link to comment Share on other sites More sharing options...
fortnox007 Posted September 9, 2010 Share Posted September 9, 2010 cool! ty for sharing Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.