Search and replace inside an associative array - php

I need to search and replace inside an associative array.
ex:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
I want to replace search1 for search4. How can I achieve this?
UPDATE: I forgot to mention that the array has several search1 values and I just want to change the value where the key is == $user. Sorry for not mention this earlier.

$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1') $myarray[$key] = 'search4';
}

There's a function for this : array_map().
// Using a lamba function, PHP 5.3 required
$newarray = array_map(
function($v) { if ($v == 'search1') $v = 'search4'; return $v; },
$myarray
);
If you don't want to use a lambda function, define a normal function or method and callback to it.

Why not just do
if (isset($myarray[$user])) $myarray[$user] = 'search4';

$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' and $key == $user )
{
$myarray[$key] = 'search4';
break;
}
}
print_r($myarray);
Prints:
Array
(
[user1] => search4
[user2] => search2
[user3] => search1
)

$originalArray = array( "user1" => "search1" , "user2" => "search2" );
$pattern = 'search1';
$replace = 'search4';
$replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );
Fixes the risk mentioned in comment in response to this solution

Updated
Since the post was updated, and I have had chance to get some sleep, I realized my answer was stupid. If you have a given key and you need to change it's value, why iterate over the whole array?
$user = 'user1';
$search = 'search1';
$replace = 'search4';
$array = array('user1' => 'search1', 'user2' => 'search2');
if (isset($array[$user]) && $search === $array[$user]) $array[$user] = $replace;
Similar to #Joseph's method (pretty much the same), but with a few tweaks:
$user = 'user1';
$array = array("user1" => "search1", "user2" => "search2" );
foreach($array as $key => &$value) {
if ($key === $user) {
$value = 'search4';
break; // Stop iterating after key has been found
}
}
Passing by reference is a nicer way to edit inside foreach, and is arguably quicker.

Search and replace inside an associative array or numeric
Replace value in any associative array and array can be any deep
function array_value_replace($maybe_array, $replace_from, $replace_to) {
if (!empty($maybe_array)) {
if (is_array($maybe_array)) {
foreach ($maybe_array as $key => $value) {
$maybe_array[$key] = array_value_replace($value, $replace_from, $replace_to);
}
} else {
if(is_string($maybe_array)){
$maybe_array = str_replace($replace_from, $replace_to, $maybe_array);
}
}
}
return $maybe_array;
}

if you want for particular key then you just add condition for key in previous ans like.
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
}

Using str_replace should work:
$myarray = array("user1" => "search1", "user2" => "search2" ) ;
$newArray = str_replace('search1', 'search4', $myarray);

Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:
function pregReplaceInArray($pattern,$replacement,$array) {
foreach ($array as $key => $value) {
$array[$key] = preg_replace($pattern,$replacement,$value);
}
return $array;
}

Related

Search in a multidimensional assoc array

I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.

PHP - multidimensional array to query string

Searched for so long but didn't get any feasible answer.
A) Input:
$array = array(
'order_source' => array('google','facebook'),
'order_medium' => 'google-text'
);
Which looks like:
Array
(
[order_source] => Array
(
[0] => google
[1] => facebook
)
[order_medium] => google-text
)
B) Required output:
order_source=google&order_source=facebook&order_medium=google-text
C) What I've tried (http://3v4l.org/b3OYo):
$arr = array('order_source' => array('google','facebook'), 'order_medium' => 'google-text');
function bqs($array, $qs='')
{
foreach($array as $par => $val)
{
if(is_array($val))
{
bqs($val, $qs);
}
else
{
$qs .= $par.'='.$val.'&';
}
}
return $qs;
}
echo $qss = bqs($arr);
D) What I'm getting:
order_medium=google-text&
Note: It should also work for any single dimensional array like http_build_query() works.
I hope that this is what you are looking for, it works with single to n-dimensinal arrays.
$walk = function( $item, $key, $parent_key = '' ) use ( &$output, &$walk ) {
is_array( $item )
? array_walk( $item, $walk, $key )
: $output[] = http_build_query( array( $parent_key ?: $key => $item ) );
};
array_walk( $array, $walk );
echo implode( '&', $output ); // order_source=google&order_source=facebook&order_medium=google-text
You don't really need to do anything special here.
$array = array(
'order_source' => array('google', 'facebook'),
'order_medium' => 'google-text'
);
$qss = http_build_query($array);
On the other side:
var_dump($_GET);
Result:
array(2) {
["order_source"]=>
array(2) {
[0]=>
string(6) "google"
[1]=>
string(8) "facebook"
}
["order_medium"]=>
string(11) "google-text"
}
This really is the best way to send arrays as GET variables.
If you absolutely must have the output as you've defined, this will do it:
function bqs($array, $qs = false) {
$parts = array();
if ($qs) {
$parts[] = $qs;
}
foreach ($array as $key => $value) {
if (is_array($value)) {
foreach ($value as $value2) {
$parts[] = http_build_query(array($key => $value2));
}
} else {
$parts[] = http_build_query(array($key => $value));
}
}
return join('&', $parts);
}
Although as you found in the comments if you are trying to pass this as $_GET you will have override problems, the solution to your problem to get desired results using recursive functions would be:
function bqs($array, $qs='',$index = false)
{
foreach($array as $par => $val)
{
if($index)
$par = $index;
if(is_array($val))
{
$qs = bqs($val, $qs,$par);
}
else
{
$qs .= $par.'='.$val.'&';
}
}
return $qs;
}
where i am concatinating the $qs string if it's an array and passing the index as a reference along with the value if it's an array()
fixed
After supplying the $index you do not need to concatenate again. See here: http://3v4l.org/QHF5G

Default values for Associative array in PHP

I have a function that accepts an array parameter as
array('employee_name' => 'employee_location' )
eg:
array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )
I wish to keep 'U.S' as the default location and a optional value, so
So If I pass
array('John', 'Dave' => 'Australia', 'Unitech')
Is there a in-build function in PHP that automatically converts it to
array('John' => 'U.S', 'Dave' => 'Australia', 'Unitech' => 'U.S' )
There is no built-in function for that.
You should loop through your array and check if the key is numeric. If it is, use the value as the key and add your default as the value.
Simple example (using a new array for clarity):
$result = array();
foreach ($arr as $key => $value)
{
if (is_int($key)) // changed is_numeric to is_int as that is more correct
{
$result[$value] = $default_value;
}
else
{
$result[$key] = $value;
}
}
Obviously this would break on duplicate names.
Note that MI6 will hunt you down: $agents = array('007' => 'UK'); will be transformed into $agents['UK'] => 'US'... I know UK and US have a "special relation", but this is taking things a tad far, IMHO.
$agents = array('007' => 'UK');
$result = array();
foreach($agents as $k => $v)
{
if (is_numeric($k))//leave this out, of course
{
echo $k.' won\'t like this';//echoes 007 won't like this
}//replace is_numeric with is_int or gettype($k) === 'integer'
if (is_int($k))
{//'007' isn't an int, so this won't happen
$result[$v] = $default;
continue;
}
$result[$k] = $v;
}
Result and input look exactly alike in this example.
foreach ($arr as $k => $v) {
if (is_int($k)) {
unset($arr[$k]);
$arr[$v] = 'U.S.';
}
}
I would work with something like this:
foreach ( $array AS $key => $value )
{
if ( is_numeric($key) )
{
$key = 'U.S';
}
$array[$key] = $value;
}

Reverse flatted array to multidimensional

In another thread i asked about flatten an array with a specific style to get something like this:
array(4) {
["one"]=> string(9) "one_value"
["two-four"]=> string(10) "four_value"
["two-five"]=> string(10) "five_value"
["three-six-seven"]=> string(11) "seven_value"
}
I've got some very good help there, but now im wondering how would i reverse this method to get again the same original array:
array(
'one' => 'one_value',
'two' => array
(
'four' => 'four_value',
'five' => 'five_value'
),
'three' => array
(
'six' => array
(
'seven' => 'seven_value'
)
)
)
I've tried with recursive method but with no luck.
I thank all the help in advance!
function expand($flat) {
$result = array();
foreach($flat as $key => $val) {
$keyParts = explode("-", $key);
$currentArray = &$result;
for($i=0; $i<count($keyParts)-1; $i++) {
if(!isSet($currentArray[$keyParts[$i]])) {
$currentArray[$keyParts[$i]] = array();
}
$currentArray = &$currentArray[$keyParts[$i]];
}
$currentArray[$keyParts[count($keyParts)-1]] = $val;
}
return $result;
}
Note that the code above is not tested and is given only to illustrate the idea.
The & operator is used for $currentArray to store not the value but the reference to some node in your tree (implemented by multidimensional array), so that changing $currentArray will change $result as well.
Here is an efficient recursive solution:
$foo = array(
"one" => "one_value",
"two-four" => "four_value",
"two-five" => "five_value",
"three-six-seven" => "seven_value"
);
function reverser($the_array) {
$temp = array();
foreach ($the_array as $key => $value) {
if (false != strpos($key, '-')) {
$first = strstr($key, '-', true);
$rest = strstr($key, '-');
if (isset($temp[$first])) {
$temp[$first] = array_merge($temp[$first], reverser(array(substr($rest, 1) => $value)));
} else {
$temp[$first] = reverser(array(substr($rest, 1) => $value));
}
} else {
$temp[$key] = $value;
}
}
return $temp;
}
print_r(reverser($foo));
strstr(___, ___, true) only works with PHP 5.3 or greater, but if this is a problem, there's a simple one-line solution (ask if you'd like it).

PHP rename array keys in multidimensional array

In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.

Categories