Modify key in array php

How to rename sub-array keys in PHP? [duplicate]

I would like to rename all array keys called «url» to be called «value». What would be a good way to do this?

14 Answers 14

$tags = array_map(function($tag) < return array( 'name' =>$tag['name'], 'value' => $tag['url'] ); >, $tags); 

quick note: You need to be using PHP 5.6 or greater, otherwise you’re running an unsupported version of php and can possibly expect security issues.

Hello, I have a case with several columns, is there a way to use similar function that does not overwrite each item, but just alter? So much coding else.

Loop through, set new key, unset old key.

Talking about functional PHP, I have this more generic answer:

Recursive php rename keys function:

function replaceKeys($oldKey, $newKey, array $input) < $return = array(); foreach ($input as $key =>$value) < if ($key===$oldKey) $key = $newKey; if (is_array($value)) $value = replaceKeys( $oldKey, $newKey, $value); $return[$key] = $value; >return $return; > 

This is a brilliant solution! it renames the key wherever it is in the multi-dimensional array. Thank you this saved me hours of work.

Warning: Reference of $row and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). Otherwise you may experience unexpected behavior. See secure.php.net/manual/en/control-structures.foreach.php, stackoverflow.com/q/3307409, stackoverflow.com/q/4969243

At least you don’t use $row after the iteration and foreach is executed inside a function, it will automatically destroyed after the end of function. Sometime $row can be useful if you have break the iteration and want to use the last iterated element outside foreach .

This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.

Also the foreach examples will throw a warning when using strict PHP error handling.

Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.

function multi_rename_key(&$array, $old_keys, $new_keys) < if(!is_array($array))< ($array=="") ? $array=array() : false; return $array; >foreach($array as &$arr) < if (is_array($old_keys)) < foreach($new_keys as $k =>$new_key) < (isset($old_keys[$k])) ? true : $old_keys[$k]=NULL; $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null); unset($arr[$old_keys[$k]]); >>else < $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null); unset($arr[$old_keys]); >> return $array; > 

Usage is simple. You can either change a single key like in your example:

multi_rename_key($tags, "url", "value"); 

or a more complex multikey

multi_rename_key($tags, array("url","name"), array("value","title")); 

It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.

Use this all the time, hope it helps!

Источник

3 Ways to Change Array Key without Changing the Order in PHP

DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.

Читайте также:  Область видимости python задачи

You can change array key too easily but doing it without changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn’t change the position of the new key at the place of old in the array.

So in this article, I have explained 3 ways to let you change array key while maintaining the key order and last one of them can be used with a multidimensional array as well. But before that, if you just need to rename a key without preserving the order, the two lines code does the job:

Change Array Key without Changing the Order in PHP

1. Change Array Key using JSON encode/decode

It’s short but be careful while using it. Use only to change key when you’re sure that your array doesn’t contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.

2. Replace key & Maintain Order using Array Functions in PHP

The function replace_key() first checks if old key exists in the array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP array_search() function.

Finally, array_combine() function returns a new array with key changed, taking keys from the created indexed array and values from source array. The non-existence of old key just simply returns the array without any change.

3. Change Array Key without Changing the Order (Multidimensional Array Capable)

This solution is quite elegant and can work with multidimensional array too with help of classic PHP loop and recursive function call. Let’s see how are we doing this change.

Here we need to pass two arrays in the function call (Line #20). The first parameter is the array which needs to change keys and another is an array containing indexes as old keys and values as new keys. Upon execution, the function will change all the keys in the first array which are present in the second array too and their respective values will be new keys.

The recursive calling within function ensures changing keys up to the deepest branch of the array. The function recursive_change_key() here is provided along with the example to understand better.

Don’t forget to read our extensive list of 38 PHP related tutorials yet.

So here you got 3 ways to change array key without changing the order of array in PHP. And the last one works with a multidimensional array as well. All you need is just to provide correct set of “old key, new key” pairs for changing purpose.

13 COMMENTS

Method 2 will fail if you have mixed key with a 0 index, as array_search without the strict flag will match 0 to any non numerical stirng.
I added a check for a numerical string and cast it to int:
public function replace_key( array $array, $oldKey, $newKey ) : array
if ( ! array_key_exists( $oldKey, $array ) )
return $array;
> $keys = array_keys( $array ); if ( is_string( $oldKey ) && is_numeric( $oldKey ) && strpos( $oldKey, ‘.’ ) === false )
$oldKey = (int) $oldKey;
> $keys[ array_search( $oldKey, $keys, true ) ] = $newKey;
return array_combine( $keys, $array );
> PHP Unit test ->
public function testRenameKeyPreservingOrder() : void
$array = [
‘a’ => ‘ay’,
0 => ‘zero’,
‘b’ => ‘be’,
‘1.1’ => ‘one point one’,
‘c’ => ‘ce’,
3 => ‘three’,
]; // Check nothing happens if the key isn’t present
$this->assertSame( $array, \TGHelpers_Array::renameKeyKeepingOrder( $array, ‘foo’, ‘bar’ ) ); // Check string keys
$this->assertSame(
[
‘a’ => ‘ay’,
0 => ‘zero’,
‘buh’ => ‘be’,
‘1.1’ => ‘one point one’,
‘c’ => ‘ce’,
3 => ‘three’,
],
\TGHelpers_Array::renameKeyKeepingOrder( $array, ‘b’, ‘buh’ )
); // Check “float” (string) keys
$this->assertSame(
[
‘a’ => ‘ay’,
0 => ‘zero’,
‘b’ => ‘be’,
‘5’ => ‘one point one’,
‘c’ => ‘ce’,
3 => ‘three’,
],
\TGHelpers_Array::renameKeyKeepingOrder( $array, ‘1.1’, 5 )
); // Check numerical
$this->assertSame(
[
‘a’ => ‘ay’,
0 => ‘zero’,
‘b’ => ‘be’,
‘1.1’ => ‘one point one’,
‘c’ => ‘ce’,
5 => ‘three’,
],
\TGHelpers_Array::renameKeyKeepingOrder( $array, 3, 5 )
); // Check numerical as string
$this->assertSame(
[
‘a’ => ‘ay’,
0 => ‘zero’,
‘b’ => ‘be’,
‘1.1’ => ‘one point one’,
‘c’ => ‘ce’,
5 => ‘three’,
],
\TGHelpers_Array::renameKeyKeepingOrder( $array, ‘3’, 5 )
);
>

Читайте также:  Python if else array

Edit: ( in the unit test \TGHelpers_Array::renameKeyKeepingOrder is where i put the function replace_key() )

A little bit more complicated, but can do associative arrays with out having to create a new array: http://php.net/manual/en/function.array-walk.php#122991

@ellisgl:disqus That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.

@ellisgl:disqus That’s good. Yet that piece of code requires more processing time as well as passing many parameters which isn’t less than memory occupied by the temporary array created here.

Источник

Change key in associative array in PHP [duplicate]

How would I change the keys of the inside arrays? Say, I want to change «n» for «name» and «l» for «last_name». Taking into account that it can happen than an array doesn’t have a particular key.

10 Answers 10

Something like this maybe:

NOTE: this solution will change the order of the keys. To preserve the order, you’d have to recreate the array.

I can see this working inside the foreach, but once outside it seems the values are still the old ones. I guess I needed to add «&».

  1. an array that maps the key exchange (to make the process parametrizable)
  2. a loop the processes the original array, accessing to every array item by reference
$array = array( array('n'=>'john','l'=>'red'), array('n'=>'nicel','l'=>'blue') ); $mapKeyArray = array('n'=>'name','l'=>'last_name'); foreach( $array as &$item ) < foreach( $mapKeyArray as $key =>$replace ) < if (key_exists($key,$item)) < $item[$replace] = $item[$key]; unset($item[$key]); >> > 

In such a way, you can have other replacements simply adding a couple key/value to the $mapKeyArray variable.

This solution also works if some key is not available in the original array

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair.

Renaming the key AND keeping the ordering consistent (the later was important for the use case that the following code was written).

 return !trigger_error('Old key does not exist', E_USER_WARNING); > else < if (array_key_exists($newKey, $data)) < if ($replaceExisting) < unset($data[$newKey]); >else < return !trigger_error('New key already exists', E_USER_WARNING); >> $keys = array_keys($data); $keys[array_search($oldKey, array_map('strval', $keys))] = $newKey; $data = array_combine($keys, $data); return true; > > return false; > 

And some unit tests (PHPUnit being used, but hopefully understandable as the purpose of the tests).

public function testRenameKey() < $newData = $this->data; $this->assertTrue(Arrays::renameKey($newData, 200, 'TwoHundred')); $this->assertEquals( [ 100 => $this->one, 'TwoHundred' => $this->two, 300 => $this->three, ], $newData ); > public function testRenameKeyWithEmptyData() < $newData = []; $this->assertFalse(Arrays::renameKey($newData, 'junk1', 'junk2')); > public function testRenameKeyWithExistingNewKey() < Arrays::renameKey($this->data, 200, 200); $this->assertError('New key already exists', E_USER_WARNING); > public function testRenameKeyWithMissingOldKey() < Arrays::renameKey($this->data, 'Unknown', 'Unknown'); $this->assertError('Old key does not exist', E_USER_WARNING); > public function testRenameKeyWithMixedNumericAndStringIndicies() < $data = [ 'nice', // Index 0 'car' =>'fast', 'none', // Index 1 ]; $this->assertTrue(Arrays::renameKey($data, 'car', 2)); $this->assertEquals( [ 0 => 'nice', 2 => 'fast', 1 => 'none', ], $data ); > 

Источник

Читайте также:  Ширина 100 процентов css

Change array key without changing order

But this will move the key to the end of the array. Is there some elegant way to change the key without changing the order? (PS: This question is just out of conceptual interest, not because I need it anywhere.)

I’m not a PHP programmer, but what in the world are the semantics of $arr[$oldKey] if this works as an argument to a function which removes $oldKey from $arr ? I think PHP might be more interesting than I previously thought, will have to look into this …

@FelixDombek I’m not sure I get you. $array[$oldKey] will just return the value with the key $oldKey .

@NikiC That’s what I also thought, but if it evaluates to, say, 5, then how does unset() delete the element from the array? How does PHP even know in which array it should delete the value 5?

8 Answers 8

function replace_key($array, $old_key, $new_key) < $keys = array_keys($array); if (false === $index = array_search($old_key, $keys, true)) < throw new Exception(sprintf('Key "%s" does not exist', $old_key)); >$keys[$index] = $new_key; return array_combine($keys, array_values($array)); > $array = [ 'a' => '1', 'b' => '2', 'c' => '3' ]; $new_array = replace_key($array, 'b', 'e'); 

Something like this may also work:

$langs = array("EN" => "English", "ZH" => "Chinese", "DA" => "Danish", "NL" => "Dutch", "FI" => "Finnish", "FR" => "French", "DE" => "German"); $json = str_replace('"EN":', '"en":', json_encode($langs)); print_r(json_decode($json, true)); 
Array ( [en] => English [ZH] => Chinese [DA] => Danish [NL] => Dutch [FI] => Finnish [FR] => French [DE] => German ) 

Me too. This works wonderful for removing dashes/underscores from XML tag names when using Zend_Config_XML::toArray(). In my case, the data is options for select elements w/ optgroups. My optgroup names were XML tags, and the titles had dashes. This worked well for that.

This only works because the example data is a very specific case. If the key to be replaced exists as any value then that would also be replaced. This is not a safe solution.

@PhilHilton: No where I mentioned this to be a panacea kind of solution. This is just a shorthand work around. Moreover having «EN»: (quoted string followed by colon) in value is very rare.

One way would be to simply use a foreach iterating over the array and copying it to a new array, changing the key conditionally while iterating, e.g. if $key === ‘foo’ then dont use foo but bar:

function array_key_rename($array, $oldKey, $newKey) < $newArray = []; foreach ($array as $key =>$value) < $newArray[$key === $oldKey ? $newKey : $key] = $value; >return $newArray; > 

Another way would be to serialize the array, str_replace the serialized key and then unserialize back into an array again. That isnt particular elegant though and likely error prone, especially when you dont only have scalars or multidimensional arrays.

A third way — my favorite — would be you writing array_key_rename in C and proposing it for the PHP core 😉

Источник

Оцените статью