Change all keys in array php

array_replace

array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parameters

The array in which elements are replaced.

Arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Return Values

Examples

Example #1 array_replace() example

$base = array( «orange» , «banana» , «apple» , «raspberry» );
$replacements = array( 0 => «pineapple» , 4 => «cherry» );
$replacements2 = array( 0 => «grape» );

$basket = array_replace ( $base , $replacements , $replacements2 );
print_r ( $basket );
?>

The above example will output:

Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )

See Also

  • array_replace_recursive() — Replaces elements from passed arrays into the first array recursively
  • array_merge() — Merge one or more arrays

User Contributed Notes 15 notes

// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values

$values = array
(
‘Article’ => ‘24497’ ,
‘Type’ => ‘LED’ ,
‘Socket’ => ‘E27’ ,
‘Dimmable’ => » ,
‘Wattage’ => ’10W’
);

$keys = array_fill_keys (array( ‘Article’ , ‘Wattage’ , ‘Dimmable’ , ‘Type’ , ‘Foobar’ ), » ); // wanted array with empty value

$allkeys = array_replace ( $keys , array_intersect_key ( $values , $keys )); // replace only the wanted keys

$notempty = array_filter ( $allkeys , ‘strlen’ ); // strlen used as the callback-function with 0==false

print » ;
print_r ( $allkeys );
print_r ( $notempty );

Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

/**
* @param array $array
* @param array $replacements
* @param boolean $override
* @return array
*/
function array_replace_keys(array $array, array $replacements, $override = false) foreach ($replacements as $old => $new) if(is_int($new) || is_string($new)) if(array_key_exists($old, $array)) if(array_key_exists($new, $array) && $override === false) continue;
>
$array[$new] = $array[$old];
unset($array[$old]);
>
>
>
return $array;
>

To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

$base = array( ‘id’ => NULL , ‘login’ => NULL , ‘credit’ => NULL );
$arr1 = array( ‘id’ => 2 , ‘login’ => NULL , ‘credit’ => 5 );
$arr2 = array( ‘id’ => NULL , ‘login’ => ‘john.doe’ , ‘credit’ => 100 );
$result = array_replace ( $base , $arr1 , $arr2 );

array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>

array(3) <
«id» => int(2)
«login» => NULL
«credit» => int(5)
>
*/
?>

Function array_replace «replaces elements from passed arrays into the first array» — this means replace from top-right to first, then from top-right — 1 to first, etc, etc.

Here is a simple array_replace_keys function:

/**
* This function replaces the keys of an associate array by those supplied in the keys array
*
* @param $array target associative array in which the keys are intended to be replaced
* @param $keys associate array where search key => replace by key, for replacing respective keys
* @return array with replaced keys
*/
private function array_replace_keys($array, $keys)
foreach ($keys as $search => $replace) if ( isset($array[$search])) $array[$replace] = $array[$search];
unset($array[$search]);
>
>

print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)

In some cases you might have a structured array from the database and one
of its nodes goes like this;

# a random node structure
$arr = array(
‘name’ => ‘some name’ ,
‘key2’ => ‘value2’ ,
‘title’ => ‘some title’ ,
‘key4’ => 4 ,
‘json’ => ‘[1,0,1,1,0]’
);

# capture these keys values into given order
$keys = array( ‘name’ , ‘json’ , ‘title’ );
?>

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

# string to transform
$string = «

name: %s, json: %s, title: %s

» ;

# flip keys once, we will use this twice
$keys = array_flip ( $keys );

# get values from $arr
$test = array_intersect_key ( $arr , $keys );

# still not good enough
echo vsprintf ( $string , $test );
// output —> name: some name, json: some title, title: [1,0,1,1,0]

# usage of array_replace to get exact order and save the day
$test = array_replace ( $keys , $test );

# exact output
echo vsprintf ( $string , $test );
// output —> name: some name, json: [1,0,1,1,0], title: some title

?>

I hope that this will save someone’s time.

Instead of calling this function, it’s often faster and simpler to do this instead:

$array_replaced = $array2 + $array1 ;
?>

If you need references to stay intact:

I got hit with a noob mistake. 🙂

When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂

foreach ( $array2 as $key => $val ) <
if ( is_array ( $array2 [ $key ])) <
tier_parse ( $array1 [ $key ], $array2 [ $key ]);
> else <
$array1 [ $key ] = $array2 [ $key ];
>
>
return $array1 ;
>
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( «berries» => array( «strawberry» => array( «color» => «red» , «food» => «desserts» ), «dewberry» = array( «color» => «dark violet» , «food» => «pies» ), );

$array1 [ «berries» ][ «dewberry» ] = polecat_array_replace ( $array1 [ «berries» ][ «dewberry» ], $array2 );
?>

This is will replace the value for «food» for «dewberry» with «wine».

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I’ve gained from this site.

Источник

Change all keys in an array from snake_case to PascalCase

I want to replace all index keys in a array but I need to do it only with a function like array_map() (not with a foreach) and that’s why it’s a little hard for me. Actual array:

$array = [ 'mc_gross' => 10.17, 'protection_eligibility' => 'Eligible', 'address_status' => 'unconfirmed', 'payer_id' => 'STTAC7UV2CVJ4' ]; 
$array = [ 'McGross' => 10.17, 'ProtectionEligibility' => 'Eligible', 'AddressStatus' => 'unconfirmed', 'PayerId' => 'STTAC7UV2CVJ4' ]; 
str_replace( "_", "", implode( '_', array_map( 'ucfirst', explode( '_', ucwords(strtolower($key)) ) ) ) ); 
array_walk($array, function ($value, &$key) < $key = str_replace("_", "", implode('_', array_map('ucfirst', explode('_', ucwords(strtolower($key)))))); >); 

^ I agree with DaOgre. foreach -es are simple, readable, maintainable, and probably just as fast or faster for this as anything you can come up with. But you, you could use array_combine(array_map($yourfunc,array_keys($array)),$array);

2 Answers 2

If you don’t want to use a foreach , you can use a combination of array_keys , array_map , and array_combine to achieve this.

$array = array( 'mc_gross' => 10.17, 'protection_eligibility' => 'Eligible', 'address_status' => 'unconfirmed', 'payer_id' => 'STTAC7UV2CVJ4' ); //Get keys $keys = array_keys($array); //Format keys function map($key) < return str_replace(' ', '', ucwords(str_replace('_', ' ', $key))); >//Map keys to format function $keys = array_map('map', $keys); //Use array_combine to map formatted keys to array values $array = array_combine($keys,$array); var_dump($array); 

This should output something like:

array(4)< ["McGross"]=>float(10.17) ["ProtectionEligibility"]=>string(8) "Eligible" ["AddressStatus"]=>string(11) "unconfirmed" ["PayerId"]=>string(13) "STTAC7UV2CVJ4" > 

As @Wrikken pointed out, the use of array_values is redundant and not needed. Thanks for the pointer!

Источник

Recursively change keys in array

I have this trimmer function, it recursively trims all values in array (people put tons of spaces for no reason!):

PROBLEM: I would like to add new feature: i want this function also to convert all _ (underscore) in keys to spaces. I know how to convert keys ( str_replace(‘_’, ‘ ‘, $key) ), but i have trouble to make it work in this recursive style. Input:

$_POST['Neat_key'] = ' dirty value '; 
$_POST['Neat key'] = 'dirty value'; 

Changing the key names can potentially be dangerous. Suppose the $_POST array has two keys in it, one named My Data and another named My_Data . You would have to figure out how to handle the potential key collision. In addition, later logic might rely on the keys from $_POST matching up with certain HTML controls. If you change the keys on the fly, that logic could break.

Web browser converts to $_POST[‘Word_word’]. If i will have two Word word and Word_word , there will be colision anyway.

2 Answers 2

Unfortunately, there isn’t a way to replace the keys of an array while you loop the array. This is a part of the language, the only way around it is to use a temporary array:

$my_array = array( 'test_key_1'=>'test value 1 ', 'test_key_2'=>' omg I love spaces!! ', 'test_key_3'=>array( 'test_subkey_1'=>'SPPPPAAAAACCCEEESSS. 111 ', 'testsubkey2'=>' The best part about computers is the SPACE BUTTON ' ) ); function trimmer(&$var) < if (is_array($var)) < $final = array(); foreach($var as $k=>&$v) < $k = str_replace('_', ' ', $k); trimmer($v); $final[$k] = $v; >$var = $final; > elseif (is_string($var)) < $var = trim($var); >> /* output array ( 'test key 1'=>'test value 1', 'test key 2'=>'omg I love spaces!!', 'test key 3'=>array ( 'test subkey 1'=>'SPPPPAAAAACCCEEESSS. 111', 'testsubkey2'=>'The best part about computers is the SPACE BUTTON' ) ) */ 

Источник

Changing all Keys of an Array

I want to change the keys in $row to the key associated with the matching value in $dictionary . For example, in the case above, $row would become:

$row = array( "comments" => "this is a test comment", "current_directory" => "testpath" ) 
array_map(function($key) use ($dictionary)< return array_search($key, $dictionary); >, array_keys($row)); 

Unfortunately, there will generally be more entries in $dictionary then $row and the order cannot be guaranteed

3 Answers 3

If $dictionary can be flipped, then

$dictionary = array_flip($dictionary); $result = array_combine( array_map(function($key) use ($dictionary)< return $dictionary[$key]; >, array_keys($row)), $row ); 

If not, then you will be better off doing a manual loop.

There are a couple potential «gotcha»s in the solution for your case. Since your two arrays might not have equal size, you will have to use array_search() inside a loop. Also, though it seems unlikely for your case, I would like to mention that if $dictionary has the keys: «0» or 0 then array_search() ‘s return value must be strictly checked for false . Here is the method that I recommend:

$row=array( "comments"=>"this is a test comment", "title"=>"title text", // key in $row not a value in $dictionary "current_path"=>"testpath" ); $dictionary=array( "0"=>"title", // $dictionary key equals zero (falsey) "current_directory"=>"current_path", "comments"=>"comments", "bogus2"=>"bogus2" // $dictionary value not a key in $row ); 
foreach($row as $k=>$v)< if(($newkey=array_search($k,$dictionary))!==false)< // if $newkey is not false $result[$newkey]=$v; // swap in new key >else < $result[$k]=$v; // no key swap, store unchanged element >> var_export($result); 
array ( 'comments' => 'this is a test comment', 0 => 'title text', 'current_directory' => 'testpath', ) 

Источник

Читайте также:  Python модели временных рядов
Оцените статью