Created
January 27, 2018 21:14
-
-
Save Balamir/4b22d71569a65a2b9045beab97e54732 to your computer and use it in GitHub Desktop.
This function can helps to replace an|multiple array key(s) with the new one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Single or multiple array key changer. | |
* | |
* @author Abdullah M CEYLAN | |
* @author URI http://www.abdullahceylan.com | |
* | |
* @param {array} $array Old array | |
* @param {string | array} $old_key Old array keys that can be string or array | |
* @param {string | array} $new_key New array key(s) that can be string or array | |
* @return {array} New array with replaced keys | |
*/ | |
function change_array_key( $array, $old_key, $new_key) { | |
if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; } | |
if (is_array($old_key) && !is_array($new_key)) { | |
print 'You must enter a array as a new_key!'; exit; | |
} elseif (is_array($new_key) && !is_array($old_key)) { | |
print 'You must enter a array as a old_key!'; exit; | |
} | |
$new_array = $array; | |
if (is_array($old_key)) { | |
$keyfound = false; | |
$key_index = 0; | |
foreach ($old_key as $key) { | |
if (!array_key_exists($key, $array)){ | |
$key_index++; | |
continue; | |
} | |
$keyfound = true; | |
$new_array = search_array_and_replace($new_key[$key_index], $key, $new_array); | |
$key_index++; | |
} | |
if (!$keyfound) { | |
return $array; | |
} else { | |
return $new_array; | |
} | |
} elseif (!array_key_exists($old_key, $array)){ | |
return $array; | |
} | |
return search_array_and_replace($new_key, $old_key, $array); | |
} | |
function search_array_and_replace($new_key, $old_key, $array) { | |
$keyPosition = array_search($old_key, array_keys($array)); | |
$arrayBeforeKey = array_slice($array, 0, $keyPosition); | |
$arrayAfterKey = array_slice($array, $keyPosition + 1); | |
$arrayReplaced = array($new_key => $array[$old_key]); | |
return $arrayBeforeKey + $arrayReplaced + $arrayAfterKey; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example - 1 (Multiple key changing):
Result - 1:
Example 2 (Single key changing):
Result - 2: