Skip to content

Instantly share code, notes, and snippets.

@orasik
Last active September 20, 2017 12:46
Show Gist options
  • Save orasik/bd00334c69522573beaf808bf1f02240 to your computer and use it in GitHub Desktop.
Save orasik/bd00334c69522573beaf808bf1f02240 to your computer and use it in GitHub Desktop.
[PHP] Replace values in array recursively
<?php
/**
* The following code will replace array that has values equalt to keys in another one.
* Example:
* $config = [
* 'key1' => 'value1',
* 'key2' => 'value2',
* 'subkeys' => [
* 'subkey1' => 'subvalue1',
* 'subkey2' => 'subvalue2'
* ]
* ];
*
* $parameters = [
* 'value1' => 123,
* 'value2' => 345
* ];
*
* Running the following code will make config array like this:
*
* $config = [
* 'key1' => 123,
* 'key2' => 345,
* 'subkeys' => [
* 'subkey1' => 'subvalue1',
* 'subkey2' => 'subvalue2'
* ]
* ];
*/
class Parameters {
protected $configArray;
public function __construct($array) {
$this->configArray = $array;
}
public function assignParameters(&$array) {
if (is_string($array) && array_key_exists($array, $this->configArray)) {
$configArray = $this->parameters[$configArray];
}
}
}
$config = [
'key1' => 'value1',
'key2' => 'value2',
'subkeys' => [
'subkey1' => 'subvalue1',
'subkey2' => 'subvalue2'
]
];
$parameters = [
'value1' => 123,
'value2' => 345
];
$object = new Parameters($parameters);
array_walk_recursive($config, [$object, 'assignParameters']);
print_r($config);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment