preg_split how to transform the delimiter as index using php - php

I have this cases with strings in PHP:
*nJohn*sSmith*fGeorge#*nHenry*sFord
and wish to create an array with
[name],[surname],[fathers] as indexes so it will produce
name_array[1] = (
[name] => 'John',
[surname] => 'Smith',
[fathers] => 'George'
)
name_array[2]=(
[name] => 'Henry',
[surname] => 'Ford'
)
and so on.
How to do it using preg_split in PHP??
Thanks!

I'd use preg_match_all to get the names. If your string is consistent I think you could do:
$string = '*nJohn*sSmith*fGeorge#*nHenry*sFord';
preg_match_all('/\*n(?<givenname>.*?)\*s(?<surname>.*?)(?:\*f(?<middlename>.*?))?(?:#|$)/', $string, $matches);
print_r($matches);
Regex demo: https://regex101.com/r/1hKzvM/1/
PHP demo: https://eval.in/784879

Solution without using regex:
$string = '*nJohn*sSmith*fGeorge#*nHenry*sFord';
$result = array();
$persons = explode('#', $string);
foreach ($persons as $person) {
$identials = explode('*', $person);
unset($r);
foreach ($identials as $idential) {
if(!$idential){
continue; //empty string
}
switch ($idential[0]) { //first character
case 'n':
$key = 'name';
break;
case 's':
$key = 'surename';
break;
case 'f':
$key = 'fathers';
break;
}
$r[$key] = substr($idential, 1);
}
$result[] = $r;
}

This function will produce the result that you want ! but consider it's not the only way and not the 100% correct way ! i used preg_split as u asked
function splitMyString($str){
$array_names = [];
$mainString = explode('#', $str);
$arr1 = preg_split("/\*[a-z]/", $mainString[0]);
unset($arr1[0]);
$arr1_values = array_values($arr1);
$arr1_keys = ['name','surname','fathers'];
$result1 = array_combine($arr1_keys, $arr1_values);
// second part of string
$arr2 = preg_split("/\*[a-z]/", $mainString[1]);
unset($arr2[0]);
$arr2_values = array_values($arr2);
$arr2_keys = ['name','surname'];
$arr2 = array_combine($arr2_keys, $arr2_values);
$array_names[] = $arr1;
$array_names[] = $arr2;
return $array_names;
}
// test result !
print_r(splitMyString("*nJohn*sSmith*fGeorge#*nHenry*sFord"));

thanks to all!
For some reason the site blocks my voting for some 'reputation' reason which I find not-fully democracy compliant! On the other hand who cares about democracy these days!
Nevertheless I am using solution #2, without indicating that solution 1 or 3 are not great!
Regards.
However inspired by your answers I came up with mine also, here it is!
$string = '*nJohn*sSmith*fGeorge#*nHenry*sFord';
split_to_key ( $string, array('n'=>'Name','s'=>'Surname','f'=>'Middle'));
function split_to_key ( $string,$ind=array() )
{
$far=null;
$i=0;
$fbig=preg_split('/#/',$string,-1,PREG_SPLIT_NO_EMPTY);
foreach ( $fbig as $fsmall ) {
$f=preg_split('/\*/u',$fsmall,-1,PREG_SPLIT_NO_EMPTY);
foreach ( $f as $fs ) {
foreach( array_keys($ind) as $key ) {
if( preg_match ('/^'.$key.'/u',$fs ) ) {
$fs=preg_replace('/^'.$key.'/u','',$fs);
$far[$i][$ind[$key]]=$fs;
}
}
}
$i++;
}
print_r($far);
}

Like Chris, I wouldn't use preg_split(). My method uses just one preg() function and one loop to completely prepare the filtered output in your desired format (notice my output is 0-indexed, though).
Input (I extended your input sample for testing):
$string='*nJohn*sSmith*fGeorge#*nHenry*sFord#*nJames*sWashington#*nMary*sMiller*fRichard';
Method (PHP Demo & Regex Demo):
if(preg_match_all('/\*n([^*]*)\*s([^*]*)(?:\*f([^#]*))?(?=#|$)/', $string, $out)){
$out=array_slice($out,1); // /prepare for array_column()
foreach($out[0] as $i=>$v){
$name_array[$i]=array_combine(['name','surname','father'],array_column($out,$i));
if($name_array[$i]['father']==''){unset($name_array[$i]['father']);}
}
}
var_export($name_array);
Output:
array (
0 =>
array (
'name' => 'John',
'surname' => 'Smith',
'father' => 'George',
),
1 =>
array (
'name' => 'Henry',
'surname' => 'Ford',
),
2 =>
array (
'name' => 'James',
'surname' => 'Washington',
),
3 =>
array (
'name' => 'Mary',
'surname' => 'Miller',
'father' => 'Richard',
),
)
My regex pattern is optimized for speed by using "negative character classes". I elected to not use the named capture groups because they nearly double the output array size from preg_match_all() and that array requires further preparation anyhow.

Related

How to check if two strings have the same beginning?

Considering I have one-dimensional ordered array of strings:
$arr = [
'Something else',
'This is option: one',
'This is option: two',
'This is option: 😜',
'This is second option: 2',
'This is second option: 3'
];
I would like to turn it into two-dimensional array, having the common beginning as the key. For example:
$target = [
'Something else',
'This is option:' => [
'one',
'two',
'😜'
],
'This is second option:' => [
'2',
'3'
]
];
It sounds simple, but I have gone completely blank.
function convertArr(array $src): array {
$prevString = null;
$newArray = [];
foreach ($src as $string) {
if ($prevString) {
// stuck here
}
$prevString = $string;
}
return $newArray;
}
Pre-made fiddle: https://3v4l.org/eqGDc
How can I check if two strings start with the same words, without having to loop on each letter?
As of now I have written this overly-complicated function, but I wonder if there is a simpler way:
function convertArr(array $src): array {
$prevString = null;
$newArray = [];
$size = count($src);
for ($i = 0; $i < $size; $i++) {
if (!$prevString || strpos($src[$i], $prevString) !== 0) {
if ($i == $size - 1) {
$newArray[] = $src[$i];
break;
}
$nowWords = explode(' ', $src[$i]);
$nextWords = explode(' ', $src[$i + 1]);
foreach ($nowWords as $k => $v) {
if ($v != $nextWords[$k]) {
break;
}
}
if ($k) {
$prevString = implode(' ', array_splice($nowWords, 0, $k));
$newArray[$prevString][] = implode(' ', $nowWords);
}
} else {
$newArray[$prevString][] = trim(substr($src[$i], strlen($prevString)));
}
}
return $newArray;
}
This might do the job:
function convertArray(array $values): array
{
$newArray = [];
foreach ($values as $value) {
if (stripos($value, ':') !== false) {
$key = strtok($value, ':');
$newArray[$key][] = trim(substr($value, stripos($value, ':') + 1));
}
}
return $newArray;
}
Essentially, based on the format of your array of strings, as long as each string only has one ":" character followed by the option value, this should work well enough.
I'm sure there will be a more advanced and more fail-safe solution but this may be a start.
I haven't got a complete solution, but maybe you can use this as a starting point: The following gets you the longest common starting sequence for the strings in an array of length 2:
var s=["This is option: one","This is option: two"];
var same=s.join('|').match(/(.*)(.*?)\|\1.*/)[1];
// same="This is option: "
In same you will find the longest possible beginning of the two strings in array s. I achieve this by using a regular expression with a greedy and a non-greedy wildcard group and forcing the first group to be repeated.
You could apply this method on slice()-d short arrays of your original sorted input array and monitor whether same stays the same for a number of these sub-arrays. You can then perform your intended grouping operation on sections with the same same.
[[ Sorry, I just realized I coded this in JavaScript and you wanted PHP - but the idea is so simple you can translate that easily into PHP yourself. ]]
Edit
When looking at the question and expected result again it seems to me, that what the OP really wants is to combine elements with similar parts before the colon (:) into a common sub-array. This can be done with the following code:
$arr = [
'Is there anything new and',
'Something old',
'This is option: one',
'This is option: two',
'This is option: 😜',
'This is second option: 2',
'This is second option: 3',
'Abc: def',
'Abc: ghi',
'the same line',
'the same words'
];
foreach($arr as $v) {
$t=array_reverse(explode(':',$v));
$target[isset($t[1])?trim($t[1]):0][]=trim($t[0]);
}
print_r($target)
output:
Array
(
[0] => Array
(
[0] => Is there anything new and
[1] => Something old
[2] => the same line
[3] => the same words
)
[This is option] => Array
(
[0] => one
[1] => two
[2] => 😜
)
[This is second option] => Array
(
[0] => 2
[1] => 3
)
[Abc] => Array
(
[0] => def
[1] => ghi
)
)
See a demo here https://rextester.com/JMB6676

PHP: Find last occurence of string in array

I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
I want $key = 3 which is the last matched element.
Any suggestion appreciated.
PHP code demo
<?php
ini_set("display_errors", 1);
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
$index=$key;
unset($Data[$key]);
}
echo $index;
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.
$data = array_flip($Data);
echo $data['bike'];
after the flip, only keep the last element of the same elements. Here is the print_r($data)
Array
(
[car] => 0
[bike] => 3
[bus] => 2
[boat] => 4
)
We can use array_reverse to reverse array.
$key = array_search('bike', array_reverse($Data,true));
It will return 3.
you can use krsort to sort the array by key.
krsort($Data);
$key = array_search('bike', $Data);
echo $key;
Working example: https://3v4l.org/fYOgN
For this I am created one function it is very easy to use. You can pass only array and parameters.
function text_to_id($value, $arr_master) {
$id_selected = 0;
$search_array = $arr_master;
if (in_array($value, $search_array)) {
$id_selected = array_search($value, $search_array);
// pr($id_selected);exit;
}
if (!$id_selected) {
foreach ($search_array as $f_key => $f_value) {
if (is_array($f_value)) {
if (in_array($value, $f_value)) {
$id_selected = $f_key;
break;
}
} else if ($value == $f_value) {
$id_selected = $f_key;
break;
}
else;
}
}
return $id_selected;
}
this function use like this
$variable = text_to_id('bike', $your_array);

Sort array based on number in value

I have an array that looks like this:
Array
(
[0] => ripe#hobby.nl 20140827
[1] => bas#hobby.nl 20130827
[2] => bas#dikkenberg.net 20140825
[3] => bas#hobby.nl 20120825
[4] => ripe#hobby.nl 20140826
)
Now i want to sort this array in php based on the numbers only so ignoring the e-mail adres in the sort process.
For example, assuming entries are always like email space number:
usort($ary, function($a, $b) {
$a = intval(explode(' ', $a)[1]);
$b = intval(explode(' ', $b)[1]);
return $a - $b;
});
or in more complicated but efficient way using Schwartzian transform:
$ary = array_map(function($x) {
return [intval(explode(' ', $x)[1]), $x];
}, $ary);
sort($ary);
$ary = array_map(function($x) {
return $x[1];
}, $ary);
<?php
$data = Array(0 => 'ripe#hobby.nl 20140827',
1 => 'bas#hobby.nl 20130827',
2 => 'bas#dikkenberg.net 20140825',
3 => 'bas#hobby.nl 20120825',
4 => 'ripe#hobby.nl 20140826'
);
$count_data = count($data);
for($i=0;$i<$count_data;$i++)
{
$new_data[trim(strstr($data[$i], ' '))]=$data[$i];
}
echo "<pre>"; print_r($new_data);
?>
this will return you
Array
(
[20140827] => ripe#hobby.nl 20140827
[20130827] => bas#hobby.nl 20130827
[20140825] => bas#dikkenberg.net 20140825
[20120825] => bas#hobby.nl 20120825
[20140826] => ripe#hobby.nl 20140826
)
Now you can sort according to need by Key
You could loop through the array, explode the string on a space, ' ', then set part one $explodedString[1] as the key in a new array, then use ksort on the new array.
Untested code.
$oldArr;
$newArr = array();
foreach($oldArr as $oldStr){
$tmpStr = explode(' ', $oldStr);
$newArr[$tmpStr[1]] = $tmp[0]; //You could use $oldStr if you still needed the numbers.
}
ksort($newArr);

Translate a string with point separated into array keys

I have an string (like one.two.three or month.2) and I need to translate this string exploding point character into array keys.
So I have month.2 and I need the codeline to translate this string into $lang['month'][2]
I was looking for that solution but I am not able to find it, I am blocked.
I finally found this:
<?php
$lang['one']['two']['three'] = 'well done';
$str = 'one.two.three';
$list = explode('.', $str);
$result = '$lang';
foreach ($list as $item)
{
$result .= '["'.$item.'"]';
}
var_dump(eval("return " . $result.';'));
?>
Start by exploding it:
$in = explode('.', $in);
Then rewrite it as a nested array:
$arg = array();
foreach (array_reverse($in) as $key) {
$arg = array($key => $arg);
}
And finally merge:
$out = array_merge_recursive($arg, $out);
Edit: in case you're seeking to read the array instead, then bazmegakapa's answer is what you're looking for.
I wrote a little recursive function to handle this. First you explode the string, and pass the array ($lang in your example, $a in mine) and this exploded array to GetVal(). It will do its best to return the needed value into $x.
$s="month.2";
$keys=explode('.', $s);
$a=array(
'month' => array('1' => 'fos', '2' => 'fos2'),
'retek' => 1
);
function GetVal($array, $keyarray) {
$key=array_shift($keyarray);
if (array_key_exists($key, $array)) {
if (count($keyarray)==0) {
return $array[$key];
} else {
return GetVal($array[$key], $keyarray);
}
} else {
return null;
}
}
$x=GetVal($a, $keys);
var_dump($x);
Its a clarification for the use of explode function:
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
this code explodes as:
Array
(
[0] => Hello
[1] => world.
[2] => It's
[3] => a
[4] => beautiful
[5] => day.
)
not as Array[hello][world][its][a].......

Replace keys in an array based on another lookup/mapping array

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.
I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values.
Here is a function that does just that:
function change_key( $array, $old_key, $new_key ) {
if( ! array_key_exists( $old_key, $array ) )
return $array;
$keys = array_keys( $array );
$keys[ array_search( $old_key, $keys ) ] = $new_key;
return array_combine( $keys, $array );
}
if your array is built from a database query, you can change the key directly from the mysql statement:
instead of
"select ´id´ from ´tablename´..."
use something like:
"select ´id´ **as NEWNAME** from ´tablename´..."
The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer
$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);
$array = [
'old1' => 1
'old2' => 2
];
$renameMap = [
'old1' => 'new1',
'old2' => 'new2'
];
$array = array_combine(array_map(function($el) use ($renameMap) {
return $renameMap[$el];
}, array_keys($array)), array_values($array));
/*
$array = [
'new1' => 1
'new2' => 2
];
*/
You could use a second associative array that maps human readable names to the id's. That would also provide a Many to 1 relationship. Then do something like this:
echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];
If you want also the position of the new array key to be the same as the old one you can do this:
function change_array_key( $array, $old_key, $new_key) {
if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; }
if(!array_key_exists($old_key, $array)){
return $array;
}
$key_pos = array_search($old_key, array_keys($array));
$arr_before = array_slice($array, 0, $key_pos);
$arr_after = array_slice($array, $key_pos + 1);
$arr_renamed = array($new_key => $array[$old_key]);
return $arr_before + $arr_renamed + $arr_after;
}
Simple benchmark comparison of both solution.
Solution 1 Copy and remove (order lost, but way faster) https://stackoverflow.com/a/240676/1617857
<?php
$array = ['test' => 'value', ['etc...']];
$array['test2'] = $array['test'];
unset($array['test']);
Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857
<?php
$array = ['test' => 'value', ['etc...']];
$keys = array_keys( $array );
$keys[array_search('test', $keys, true)] = 'test2';
array_combine( $keys, $array );
Benchmark:
<?php
$array = ['test' => 'value', ['etc...']];
for ($i =0; $i < 100000000; $i++){
// Solution 1
}
for ($i =0; $i < 100000000; $i++){
// Solution 2
}
Results:
php solution1.php 6.33s user 0.02s system 99% cpu 6.356 total
php solution1.php 6.37s user 0.01s system 99% cpu 6.390 total
php solution2.php 12.14s user 0.01s system 99% cpu 12.164 total
php solution2.php 12.57s user 0.03s system 99% cpu 12.612 total
If your array is recursive you can use this function:
test this data:
$datos = array
(
'0' => array
(
'no' => 1,
'id_maquina' => 1,
'id_transaccion' => 1276316093,
'ultimo_cambio' => 'asdfsaf',
'fecha_ultimo_mantenimiento' => 1275804000,
'mecanico_ultimo_mantenimiento' =>'asdfas',
'fecha_ultima_reparacion' => 1275804000,
'mecanico_ultima_reparacion' => 'sadfasf',
'fecha_siguiente_mantenimiento' => 1275804000,
'fecha_ultima_falla' => 0,
'total_fallas' => 0,
),
'1' => array
(
'no' => 2,
'id_maquina' => 2,
'id_transaccion' => 1276494575,
'ultimo_cambio' => 'xx',
'fecha_ultimo_mantenimiento' => 1275372000,
'mecanico_ultimo_mantenimiento' => 'xx',
'fecha_ultima_reparacion' => 1275458400,
'mecanico_ultima_reparacion' => 'xx',
'fecha_siguiente_mantenimiento' => 1275372000,
'fecha_ultima_falla' => 0,
'total_fallas' => 0,
)
);
here is the function:
function changekeyname($array, $newkey, $oldkey)
{
foreach ($array as $key => $value)
{
if (is_array($value))
$array[$key] = changekeyname($value,$newkey,$oldkey);
else
{
$array[$newkey] = $array[$oldkey];
}
}
unset($array[$oldkey]);
return $array;
}
I like KernelM's solution, but I needed something that would handle potential key conflicts (where a new key may match an existing key). Here is what I came up with:
function swapKeys( &$arr, $origKey, $newKey, &$pendingKeys ) {
if( !isset( $arr[$newKey] ) ) {
$arr[$newKey] = $arr[$origKey];
unset( $arr[$origKey] );
if( isset( $pendingKeys[$origKey] ) ) {
// recursion to handle conflicting keys with conflicting keys
swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );
unset( $pendingKeys[$origKey] );
}
} elseif( $newKey != $origKey ) {
$pendingKeys[$newKey] = $origKey;
}
}
You can then cycle through an array like this:
$myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );
$pendingKeys = array();
foreach( $myArray as $key => $myArrayValue ) {
// NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)
$timestamp = strtotime( $myArrayValue );
swapKeys( $myArray, $key, $timestamp, $pendingKeys );
}
// RESULT: $myArray == array( 1=>'1970-01-01 00:00:01', 60=>'1970-01-01 00:01:00' )
Here is a helper function to achieve that:
/**
* Helper function to rename array keys.
*/
function _rename_arr_key($oldkey, $newkey, array &$arr) {
if (array_key_exists($oldkey, $arr)) {
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
return TRUE;
} else {
return FALSE;
}
}
pretty based on #KernelM answer.
Usage:
_rename_arr_key('oldkey', 'newkey', $my_array);
It will return true on successful rename, otherwise false.
this code will help to change the oldkey to new one
$i = 0;
$keys_array=array("0"=>"one","1"=>"two");
$keys = array_keys($keys_array);
for($i=0;$i<count($keys);$i++) {
$keys_array[$keys_array[$i]]=$keys_array[$i];
unset($keys_array[$i]);
}
print_r($keys_array);
display like
$keys_array=array("one"=>"one","two"=>"two");
Easy stuff:
this function will accept the target $hash and $replacements is also a hash containing newkey=>oldkey associations.
This function will preserve original order, but could be problematic for very large (like above 10k records) arrays regarding performance & memory.
function keyRename(array $hash, array $replacements) {
$new=array();
foreach($hash as $k=>$v)
{
if($ok=array_search($k,$replacements))
$k=$ok;
$new[$k]=$v;
}
return $new;
}
this alternative function would do the same, with far better performance & memory usage, at the cost of losing original order (which should not be a problem since it is hashtable!)
function keyRename(array $hash, array $replacements) {
foreach($hash as $k=>$v)
if($ok=array_search($k,$replacements))
{
$hash[$ok]=$v;
unset($hash[$k]);
}
return $hash;
}
This page has been peppered with a wide interpretation of what is required because there is no minimal, verifiable example in the question body. Some answers are merely trying to solve the "title" without bothering to understand the question requirements.
The key is actually an ID number and the value is a count. This is
fine for most instances, however I want a function that gets the
human-readable name of the array and uses that for the key, without
changing the value.
PHP keys cannot be changed but they can be replaced -- this is why so many answers are advising the use of array_search() (a relatively poor performer) and unset().
Ultimately, you want to create a new array with names as keys relating to the original count. This is most efficiently done via a lookup array because searching for keys will always outperform searching for values.
Code: (Demo)
$idCounts = [
3 => 15,
7 => 12,
8 => 10,
9 => 4
];
$idNames = [
1 => 'Steve',
2 => 'Georgia',
3 => 'Elon',
4 => 'Fiona',
5 => 'Tim',
6 => 'Petra',
7 => 'Quentin',
8 => 'Raymond',
9 => 'Barb'
];
$result = [];
foreach ($idCounts as $id => $count) {
if (isset($idNames[$id])) {
$result[$idNames[$id]] = $count;
}
}
var_export($result);
Output:
array (
'Elon' => 15,
'Quentin' => 12,
'Raymond' => 10,
'Barb' => 4,
)
This technique maintains the original array order (in case the sorting matters), doesn't do any unnecessary iterating, and will be very swift because of isset().
If you want to replace several keys at once (preserving order):
/**
* Rename keys of an array
* #param array $array (asoc)
* #param array $replacement_keys (indexed)
* #return array
*/
function rename_keys($array, $replacement_keys) {
return array_combine($replacement_keys, array_values($array));
}
Usage:
$myarr = array("a" => 22, "b" => 144, "c" => 43);
$newkeys = array("x","y","z");
print_r(rename_keys($myarr, $newkeys));
//must return: array("x" => 22, "y" => 144, "z" => 43);
You can use this function based on array_walk:
function mapToIDs($array, $id_field_name = 'id')
{
$result = [];
array_walk($array,
function(&$value, $key) use (&$result, $id_field_name)
{
$result[$value[$id_field_name]] = $value;
}
);
return $result;
}
$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
print_r($arr);
print_r(mapToIDs($arr));
It gives:
Array(
[0] => Array(
[id] => one
[fruit] => apple
)
[1] => Array(
[id] => two
[fruit] => banana
)
)
Array(
[one] => Array(
[id] => one
[fruit] => apple
)
[two] => Array(
[id] => two
[fruit] => banana
)
)
This basic function handles swapping array keys and keeping the array in the original order...
public function keySwap(array $resource, array $keys)
{
$newResource = [];
foreach($resource as $k => $r){
if(array_key_exists($k,$keys)){
$newResource[$keys[$k]] = $r;
}else{
$newResource[$k] = $r;
}
}
return $newResource;
}
You could then loop through and swap all 'a' keys with 'z' for example...
$inputs = [
0 => ['a'=>'1','b'=>'2'],
1 => ['a'=>'3','b'=>'4']
]
$keySwap = ['a'=>'z'];
foreach($inputs as $k=>$i){
$inputs[$k] = $this->keySwap($i,$keySwap);
}
This function will rename an array key, keeping its position, by combining with index searching.
function renameArrKey($arr, $oldKey, $newKey){
if(!isset($arr[$oldKey])) return $arr; // Failsafe
$keys = array_keys($arr);
$keys[array_search($oldKey, $keys)] = $newKey;
$newArr = array_combine($keys, $arr);
return $newArr;
}
Usage:
$arr = renameArrKey($arr, 'old_key', 'new_key');
this works for renaming the first key:
$a = ['catine' => 'cat', 'canine' => 'dog'];
$tmpa['feline'] = $a['catine'];
unset($a['catine']);
$a = $tmpa + $a;
then, print_r($a) renders a repaired in-order array:
Array
(
[feline] => cat
[canine] => dog
)
this works for renaming an arbitrary key:
$a = ['canine' => 'dog', 'catine' => 'cat', 'porcine' => 'pig']
$af = array_flip($a)
$af['cat'] = 'feline';
$a = array_flip($af)
print_r($a)
Array
(
[canine] => dog
[feline] => cat
[porcine] => pig
)
a generalized function:
function renameKey($oldkey, $newkey, $array) {
$val = $array[$oldkey];
$tmp_A = array_flip($array);
$tmp_A[$val] = $newkey;
return array_flip($tmp_A);
}
There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array.
It's simply to copy the array into a new array.
For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.
I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.
<?php
$arr = [
'foo',
'bar'=>'alfa',
'baz'=>['a'=>'hello', 'b'=>'world'],
];
foreach($arr as $k=>$v) {
$kk = is_numeric($k) ? $v : $k;
$vv = is_numeric($k) ? null : $v;
$arr2[$kk] = $vv;
}
print_r($arr2);
Output:
Array (
[foo] =>
[bar] => alfa
[baz] => Array (
[a] => hello
[b] => world
)
)
best way is using reference, and not using unset (which make another step to clean memory)
$tab = ['two' => [] ];
solution:
$tab['newname'] = & $tab['two'];
you have one original and one reference with new name.
or if you don't want have two names in one value is good make another tab and foreach on reference
foreach($tab as $key=> & $value) {
if($key=='two') {
$newtab["newname"] = & $tab[$key];
} else {
$newtab[$key] = & $tab[$key];
}
}
Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..
One which preservers ordering that's simple to understand:
function rename_array_key(array $array, $old_key, $new_key) {
if (!array_key_exists($old_key, $array)) {
return $array;
}
$new_array = [];
foreach ($array as $key => $value) {
$new_key = $old_key === $key
? $new_key
: $key;
$new_array[$new_key] = $value;
}
return $new_array;
}
Here is an experiment (test)
Initial array (keys like 0,1,2)
$some_array[] = '6110';//
$some_array[] = '6111';//
$some_array[] = '6210';//
I must change key names to for example human_readable15, human_readable16, human_readable17
Something similar as already posted. During each loop i set necessary key name and remove corresponding key from the initial array.
For example, i inserted into mysql $some_array got lastInsertId and i need to send key-value pair back to jquery.
$first_id_of_inserted = 7;//lastInsertId
$last_loop_for_some_array = count($some_array);
for ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {
$some_array['human_readable'.($first_id_of_inserted + $current_loop)] = $some_array[$current_loop];//add new key for intial array
unset( $some_array[$current_loop] );//remove already renamed key from array
}
And here is the new array with renamed keys
echo '<pre>', print_r($some_array, true), '</pre>$some_array in '. basename(__FILE__, '.php'). '.php <br/>';
If instead of human_readable15, human_readable16, human_readable17 need something other. Then could create something like this
$arr_with_key_names[] = 'human_readable';
$arr_with_key_names[] = 'something_another';
$arr_with_key_names[] = 'and_something_else';
for ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {
$some_array[$arr_with_key_names[$current_loop]] = $some_array[$current_loop];//add new key for intial array
unset( $some_array[$current_loop] );//remove already renamed key from array
}
Hmm, I'm not test before, but I think this code working
function replace_array_key($data) {
$mapping = [
'old_key_1' => 'new_key_1',
'old_key_2' => 'new_key_2',
];
$data = json_encode($data);
foreach ($mapping as $needed => $replace) {
$data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
}
return json_decode($data, true);
}
You can write simple function that applies the callback to the keys of the given array. Similar to array_map
<?php
function array_map_keys(callable $callback, array $array) {
return array_merge([], ...array_map(
function ($key, $value) use ($callback) { return [$callback($key) => $value]; },
array_keys($array),
$array
));
}
$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];
$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);
echo json_encode($array); // {"a":1,"b":"test","c":{"x":1,"y":2}}
echo json_encode($newArray); // {"newA":1,"newB":"test","newC":{"x":1,"y":2}}
Here is a gist https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php.

Categories