$element) { if ($key == $beforekey) { $beforefound = true; foreach ($addelements as $addkey => $addelement) $newarray[$addkey] = $addelement; } $newarray[$key] = $element; } if (!$beforefound) { foreach ($addelements as $addkey => $addelement) $newarray[$addkey] = $addelement; } $array = $newarray; } // Special values for the $beforekey parameter for qa_array_reorder() - use floats since these cannot be real keys define('QA_ARRAY_WITH_FIRST', null); // collect the elements together in the position of the first one found define('QA_ARRAY_WITH_LAST', 0.6); // collect the elements together in the position of the last one found define('QA_ARRAY_AT_START', 0.1); // place all the elements at the start of the array define('QA_ARRAY_AT_END', 0.9); // place all the elements at the end of the array /** * Moves all of the elements in $array whose keys are in the parameter $keys. They can be moved to before a specific * element by passing the key of that element in $beforekey (if $beforekey is not found, the elements are moved to the * end of the array). Any of the QA_ARRAY_* values defined above can also be passed in the $beforekey parameter. * If $reorderrelative is true, the relative ordering between the elements will also be set by the order in $keys. * @param $array * @param $keys * @param mixed $beforekey * @param bool $reorderrelative */ function qa_array_reorder(&$array, $keys, $beforekey = null, $reorderrelative = true) { // Make a map for checking each key in $array against $keys and which gives their ordering $keyorder = array(); $keyindex = 0; foreach ($keys as $key) $keyorder[$key] = ++$keyindex; // Create the new key ordering in $newkeys $newkeys = array(); $insertkeys = array(); $offset = null; if ($beforekey == QA_ARRAY_AT_START) $offset = 0; foreach ($array as $key => $value) { if ($beforekey == $key) $offset = count($newkeys); if (isset($keyorder[$key])) { if ($reorderrelative) $insertkeys[$keyorder[$key]] = $key; // in order of $keys parameter else $insertkeys[] = $key; // in order of original array if ($beforekey == QA_ARRAY_WITH_LAST || ($beforekey === QA_ARRAY_WITH_FIRST && !isset($offset))) $offset = count($newkeys); } else $newkeys[] = $key; } if (!isset($offset)) // also good for QA_ARRAY_AT_END $offset = count($newkeys); if ($reorderrelative) ksort($insertkeys, SORT_NUMERIC); // sort them based on position in $keys parameter array_splice($newkeys, $offset, 0, $insertkeys); // Rebuild the array based on the new key ordering $newarray = array(); foreach ($newkeys as $key) $newarray[$key] = $array[$key]; $array = $newarray; }