Skip to content

Instantly share code, notes, and snippets.

@attitude
Last active December 19, 2015 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attitude/5943865 to your computer and use it in GitHub Desktop.
Save attitude/5943865 to your computer and use it in GitHub Desktop.
Function to merge new SQL argument arrays (right) with defaults (left)
<?php
/**
* Merges new SQL argument arrays with defaults
*
* Differs from {@link array_merge()} and {@link array_merge_recursive()}:
*
* 1. Array of 'where', 'orderby', 'groupby' and 'join' keys should be
* appended and remain unique.
* 2. 'select', 'limit' should be overwritten, by new argument on right
*
* Left key's values are appended to the end of key's value (important for
* `ORDER BY` priority).
*
* @param array $old Left array to merge into
* @param array $new Right array to be merged into left
* @returns array Result of merge
* @author Martin Adamko <@martin_adamko>
* @license The MIT license <http://opensource.org/licenses/MIT>
*
*/
function array_merge_for_sql(array $old, array $new)
{
static $multiple = array('where', 'orderby', 'groupby', 'join');
// Default merge: overwrites old values with new values
$out = array_merge($old, $new);
// Fix removal of old entries, appended at the end
foreach ($out as $k => &$v) {
if (in_array($k, $multiple)) {
$out[$k] = (array) $out[$k];
if (isset($old[$k])) {
$old[$k] = (array) $old[$k];
foreach ($old[$k] as $condition) {
if(!in_array($condition, $out[$k])) {
$out[$k][] = $condition;
}
}
}
} elseif (is_array($out[$k])) {
reset($out[$k]);
$out[$k] = current($out[$k]);
}
}
return $out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment