I have this string:
"[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]"
This string was formated form an array using this code:
function arrayDisplay($input)
{
return implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
);
}
And encoded using :
$xml_array = arrayDisplay($_POST);
$xml_encode = json_encode($xml_array);
And this is the array in $_POST variable:
array (size=5)
'form' => string 'form-elements' (length=13)
'company' => string 'asdasd' (length=6)
'cod_postal' => string '051768' (length=6)
'recaptcha_challenge_field' => string '03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M' (length=249)
'recaptcha_response_field' => string '168' (length=3)
First I want to wrap the entire string replacing "" with [] :
[[\"form\",\"form-elements\"], [\"company\",\"asdasd\"], [\"cod_postal\",\"051768\"], [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"], [\"recaptcha_response_field\",\"168\"]]
And exclude [\"form\",\"form-elements\"] , [\"recaptcha_challenge_field\",\"03AHJ_VuvJZjfMzRQolI_QhGijJqAEcRPswuz9l68I6VStJzTbuK4ilos06TIQKVsIy2vpe1PEq-Q5KBVlZ5xt4HM5VoJSWUgFTGVbtbmARtKiMvO4WZh57X0-QVDyQ5Lq-ZM8rMqB5O2-rCbnyw_UAGbbV1ZElsI4kuLk4ei6mzLtqgcU2VAR64tySiKPARDtahiTBKWePH2rjKO6KUBQTRE49TMjIGb5hg8sbYguKBSUrRF6G86b89M\"] and [\"recaptcha_response_field\",\"168\"]
What I can use to do that and how ?
You must filter the input. After filtering it you just return the json encoded string:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return json_encode(array($input));
}
If you still want to return the key-value pairs separated by comma then keep the original implode function and concatenate the result with the squared brackets:
function arrayDisplay($input)
{
$input = array_filter($input, function ($key) {
return !in_array($key, array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
}, ARRAY_FILTER_USE_KEY);
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$input,
array_keys($input)
)
) . ']';
}
Please note that $xml_encode = json_encode($xml_array); makes no sense as the returned string is "almost" a valid json encoded string (in the original function). If this is your intention then you must use the first function I wrote and remove that line of code that is encoding again the returned value.
You should start from your $_POST array, and take the keys from it you really need:
$input = $_POST;
unset($input["form"]);
unset($input["recaptcha_challenge_field"]);
unset($input["recaptcha_response_field"]);
Now that $input array looks like this:
array(
"company" => "asdasd",
"cod_postal" => "051768"
);
Then, I would change the definition of your arrayDisplay function without altering its functionality, by splitting it into 2:
function arrayPairs($input) {
return array_map(
function ($v, $k) {
return [$k,$v];
},
$input,
array_keys($input)
);
}
function arrayDisplay($input) {
return implode (", ", array_map('json_encode', arrayPairs($input)));
}
This arrayDisplay function still returns the same values as before, but you can now also call arrayPairs without conversion to string. Instead you would do that conversion with json_encode which gives exactly the output you want:
echo json_encode(arrayPairs($input));
This outputs:
[["company","asdasd"],["cod_postal","051768"]]
NB: If you don't use the arrayDisplay function for any other purpose, then you can do away with it. This solution only uses the function arrayPairs.
I made some changes and ended up with this:
function arrayDisplay($input)
{
$goodKeys = array_diff(array_keys($input), array('form', 'recaptcha_challenge_field', 'recaptcha_response_field'));
var_dump($goodKeys);
$data = [];
foreach ($goodKeys as $goodKey) {
$data[$goodKey] = $input[$goodKey];
}
return '[' . implode(
', ',
array_map(
function ($v, $k) {
return sprintf('["%s","%s"]', $k, $v);
},
$data,
array_keys($data)
)
) . ']';
}
but now there is one more problem, I need to get rid of "" this 2 from the start/end of the string:
from this:
"[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]"
to this:
[[\"company\",\"123\"], [\"cod_postal\",\"051768\"]]
Related
I try to convert a string containing shedule to an array
For exemple
convert("{{09:00,10:00},{18:00,19:00}}") // returns [['09:00','10:00'],['18:00','19:00']]
Is there a way more elegant than this one :
function convert($shedules) {
$shedules = explode('},{', $horaires);
$shedules = array_map(function ($shedule) {
return explode(',', str_replace(['{', '}'], '', $shedule));
}, $shedules);
return $shedules
}
Lets say I have an array like this, it could be multi-dimensional so I do need to make this loop recursive.
I think I'm close but can't quite see where I'm wrong.
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b = $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
The intended result should be:
"rigging, animation, modeling"
I'm getting just "modeling,"
In your code, you need to write
$b .= $this->_replace_amp($value); // note the period
Without the period, you are initiating $b every time your script finds a new array, but you want to append the results to $b.
Other than that, there is a nice implode function for multidimensional arrays available:
/**
* Recursively implodes an array with optional key inclusion
*
* Example of $include_keys output: key, value, key, value, key, value
*
* #access public
* #param array $array multi-dimensional array to recursively implode
* #param string $glue value that glues elements together
* #param bool $include_keys include keys before their values
* #param bool $trim_all trim ALL whitespace from string
* #return string imploded array
*/
function recursive_implode(array $array, $glue = ',', $include_keys = false, $trim_all = true)
{
$glued_string = '';
// Recursively iterates array and adds key/value to glued string
array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glued_string)
{
$include_keys and $glued_string .= $key.$glue;
$glued_string .= $value.$glue;
});
// Removes last $glue from string
strlen($glue) > 0 and $glued_string = substr($glued_string, 0, -strlen($glue));
// Trim ALL whitespace
$trim_all and $glued_string = preg_replace("/(\s)/ixsm", '', $glued_string);
return (string) $glued_string;
}
Source: https://gist.github.com/jimmygle/2564610
I think either json_encode( your_php_array ) or serialize() function is help you.
You want to use function implode(). No need to re-invent the wheel.
<?php
$arr = ['one', 'two', 'three'];
echo implode(',', $arr); // one, two, three
$b = $this->_replace_amp($value); change in this line to $b .= $this->_replace_amp($value);
this answer as per your coding
[
{ "value": "rigging" },
{ "value": "animation" },
{ "value": "modeling" }
]
function _replace_amp($post = array()) {
foreach($post as $key => $value)
{
if (is_array($value)) {
$b .= $this->_replace_amp($value);
} else {
$b .= $value . ', ';
}
}
return $b;
}
batter way to do this using used implode(',',$array);
Without foreach,
how can I turn an array like this
array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");
to a string like this
item1='object1', item2='object2',.... item-n='object-n'
I thought about implode() already, but it doesn't implode the key with it.
If foreach it necessary, is it possible to not nest the foreach?
EDIT: I've changed the string
EDIT2/UPDATE:
This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use ternary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it is concise or not doesn't matter that much.
In this case: putting the foreach in a function will be much more readable and modular than writing a one-liner(Even though all the answers are great!).
You could use http_build_query, like this:
<?php
$a=array("item1"=>"object1", "item2"=>"object2");
echo http_build_query($a,'',', ');
?>
Output:
item1=object1, item2=object2
Demo
and another way:
$input = array(
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n'
);
$output = implode(', ', array_map(
function ($v, $k) {
if(is_array($v)){
return $k.'[]='.implode('&'.$k.'[]=', $v);
}else{
return $k.'='.$v;
}
},
$input,
array_keys($input)
));
or:
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
I spent measurements (100000 iterations), what fastest way to glue an associative array?
Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"
We have array (for example):
$array = [
'test0' => 344,
'test1' => 235,
'test2' => 876,
...
];
Test number one:
Use http_build_query and str_replace:
str_replace('=', ':', http_build_query($array, null, ','));
Average time to implode 1000 elements: 0.00012930955084904
Test number two:
Use array_map and implode:
implode(',', array_map(
function ($v, $k) {
return $k.':'.$v;
},
$array,
array_keys($array)
));
Average time to implode 1000 elements: 0.0004890081976675
Test number three:
Use array_walk and implode:
array_walk($array,
function (&$v, $k) {
$v = $k.':'.$v;
}
);
implode(',', $array);
Average time to implode 1000 elements: 0.0003874126245348
Test number four:
Use foreach:
$str = '';
foreach($array as $key=>$item) {
$str .= $key.':'.$item.',';
}
rtrim($str, ',');
Average time to implode 1000 elements: 0.00026632803902445
I can conclude that the best way to glue the array - use http_build_query and str_replace
I would use serialize() or json_encode().
While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
Using array_walk
$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);
IDEONE
You could use PHP's array_reduce as well,
$a = ['Name' => 'Last Name'];
function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}
$imploded = array_reduce(array_keys($a), "acc");
Change
- return substr($result, (-1 * strlen($glue)));
+ return substr($result, 0, -1 * strlen($glue));
if you want to resive the entire String without the last $glue
function key_implode(&$array, $glue) {
$result = "";
foreach ($array as $key => $value) {
$result .= $key . "=" . $value . $glue;
}
return substr($result, (-1 * strlen($glue)));
}
And the usage:
$str = key_implode($yourArray, ",");
For debugging purposes. Recursive write an array of nested arrays to a string.
Used foreach. Function stores National Language characters.
function q($input)
{
$glue = ', ';
$function = function ($v, $k) use (&$function, $glue) {
if (is_array($v)) {
$arr = [];
foreach ($v as $key => $value) {
$arr[] = $function($value, $key);
}
$result = "{" . implode($glue, $arr) . "}";
} else {
$result = sprintf("%s=\"%s\"", $k, var_export($v, true));
}
return $result;
};
return implode($glue, array_map($function, $input, array_keys($input))) . "\n";
}
Here is a simple example, using class:
$input = array(
'element1' => 'value1',
'element2' => 'value2',
'element3' => 'value3'
);
echo FlatData::flatArray($input,', ', '=');
class FlatData
{
public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')
{
$output = implode($separator_elements, array_map(
function ($v, $k, $s) {
return sprintf("%s{$s}%s", $k, $v);
},
$input,
array_keys($input),
array_fill(0, count($input), $separator)
));
return $output;
}
}
For create mysql where conditions from array
$sWheres = array('item1' => 'object1',
'item2' => 'object2',
'item3' => 1,
'item4' => array(4,5),
'item5' => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
$sWhereConditions = array();
foreach ($sWheres as $key => $value){
if(!empty($value)){
if(is_array($value)){
$value = array_filter($value); // For remove blank values from array
if(!empty($value)){
array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
$sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
}
}else{
$sWhereConditions[] = sprintf("%s='%s'", $key, $value);
}
}
}
if(!empty($sWhereConditions)){
$sWhere .= "(".implode(' AND ', $sWhereConditions).")";
}
}
echo $sWhere; // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
Short one:
$string = implode('; ', array_map(fn($k, $v) => "$k=$v", array_keys($array), $array));
Using explode to get an array from any string is always OK, because array is an always in standard structure.
But about array to string, is there any reason to use predefined string in codes? while the string SHOULD be in any format to use!
The good point of foreach is that you can create the string AS YOU NEED IT!
I'd suggest still using foreach quiet readable and clean.
$list = array('a'=>'1', 'b'=>'2', 'c'=>'3');
$sql_val = array();
foreach ($list as $key => $value) {
$sql_val[] = "(" . $key . ", '" . $value . "') ";
}
$sql_val = implode(', ', $sql_val);
with results:
(a, '1') , (b, '2') , (c, '3')
|
(a: '1') , (b: '2') , (c: '3')
|
a:'1' , b:'2' , c:'3'
etc.
Also if the question is outdated and the solution not requested anymore, I just found myself in the need of printing an array for debugging purposes (throwing an exception and showing the array that caused the problem).
For this reason, I anyway propose my simple solution (one line, like originally asked):
$array = ['a very' => ['complex' => 'array']];
$imploded = var_export($array, true);
This will return the exported var instead of directly printing it on the screen and the var $imploded will contain the full export.
I was looking for some standard PHP function to replace some value of an array with other, but surprisingly I haven't found any, so I have to write my own:
function array_replace_value(&$ar, $value, $replacement)
{
if (($key = array_search($ar, $value)) !== FALSE) {
$ar[$key] = $replacement;
}
}
But I still wonder - for such an easy thing there must already be some function for it! Or maybe much easier solution than this one invented by me?
Note that this function will only do one replacement. I'm looking for existing solutions that similarly replace a single occurrence, as well as those that replace all occurrences.
Instead of a function that only replaces occurrences of one value in an array, there's the more general array_map:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
To replace multiple occurrences of multiple values using array of value => replacement:
array_map(function ($v) use ($replacement) {
return isset($replacement[$v]) ? $replacement[$v] : $v;
}, $arr);
To replace a single occurrence of one value, you'd use array_search as you do. Because the implementation is so short, there isn't much reason for the PHP developers to create a standard function to perform the task. Not to say that it doesn't make sense for you to create such a function, if you find yourself needing it often.
While there isn't one function equivalent to the sample code, you can use array_keys (with the optional search value parameter), array_fill and array_replace to achieve the same thing:
EDIT by Tomas: the code was not working, corrected it:
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
Try this function.
public function recursive_array_replace ($find, $replace, $array) {
if (!is_array($array)) {
return str_replace($find, $replace, $array);
}
$newArray = [];
foreach ($array as $key => $value) {
$newArray[$key] = recursive_array_replace($find, $replace, $value);
}
return $newArray;
}
Cheers!
$ar[array_search('green', $ar)] = 'value';
Depending whether it's the value, the key or both you want to find and replace on you could do something like this:
$array = json_decode( str_replace( $replace, $with, json_encode( $array ) ), true );
I'm not saying this is the most efficient or elegant, but nice and simple.
What about array_walk() with callback?
$array = ['*pasta', 'cola', 'pizza'];
$search = '*';
$replace = '\*';
array_walk($array,
function (&$v) use ($search, $replace){
$v = str_replace($search, $replace, $v);
}
);
print_r($array);
Based on Deept Raghav's answer, I created the follow solution that does regular expression search.
$arr = [
'Array Element 1',
'Array Element 2',
'Replace Me',
'Array Element 4',
];
$arr = array_replace(
$arr,
array_fill_keys(
array_keys(
preg_grep('/^Replace/', $arr)
),
'Array Element 3'
)
);
echo '<pre>', var_export($arr), '</pre>';
PhpFiddle: http://phpfiddle.org/lite/code/un7u-j1pt
PHP 8, a strict version to replace one string value with another:
array_map(fn (string $value): string => $value === $find ? $replace : $value, $array);
An example - replace value foo with bar:
array_map(fn (string $value): string => $value === 'foo' ? 'bar' : $value, $array);
You can make full string matches without specifying the keys of qualifying values, by calling preg_replace() with a pattern containing start and end of string anchors (^, $). If your search term may contain characters which have a special meaning to the regex engine, then be sure to escape them with preg_quote() to avoid breakage. While regex is not entirely called for, regex offers some very convenient ways to tweak the search term handling. (Demo)
function array_replace_value(&$ar, $value, $replacement)
{
$ar = preg_replace(
'/^' . preg_quote($value, '/') . '$/',
$replacement,
$ar
);
}
I might be more inclined to use array_map() with arrow function syntax so that global variables can be accessed within the custom function scope. (Demo)
$needle = 'foo';
$newValue = 'bar';
var_export(
array_map(fn($v) => $v === $needle ? $newValue : $v, $array)
);
$ar = array(1,2,3,4,5,6,7,8);
$find = array(2,3);
$replace = array(13);
function update_bundle_package($ar,$find,$replace){
foreach ($find as $x => $y) {
///TO REMOVE PACKAGE
if (($key = array_search($y, $ar)) !== false) {
unset($ar[$key]);
}
///TO REMOVE PACKAGE
}
$ar = array_merge($ar, $replace);
}
<b>$green_key = array_search('green', $input); // returns the first key whose value is 'green'
$input[$green_key] = 'apple'; // replace 'green' with 'apple'
How can I replace a sub string with some other string for all items of an array in PHP?
I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?
How can I do that on keys of array?
Why not just use str_replace without a loop?
$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);
$array = array_map(
function($str) {
return str_replace('foo', 'bar', $str);
},
$array
);
But array_map is just a hidden loop. Why not use a real one?
foreach ($array as &$str) {
$str = str_replace('foo', 'bar', $str);
}
That's much easier.
This is a very good idea that I found and used successfully:
function str_replace_json($search, $replace, $subject)
{
return json_decode(str_replace($search, $replace, json_encode($subject)), true);
}
It is good also for multidimensional arrays.
If you change the "true" to "false" then it will return an object instead of an associative array.
Source: Codelinks
I am not sure how efficient this is, but I wanted to replace strings in a big multidimensional array and did not want to loop through all items as the array structure is pretty dynamic.
I first json_encode the array into a string.
Replace all the strings I want (need to use preg_replace if there are non-English characters that get encoded by json_encode).
json_decode to get the array back.
function my_replace_array($array,$key,$val){
for($i=0;$i<count($array);$i++){
if(is_array($array[$i])){
$array[$i] = my_replace_array($array[$i],$key,$val);
}else{
$array[$i]=str_replace($key,$val,$array[$i]);
}
}
return $array;
}
With array_walk_recursive()
function replace_array_recursive( string $needle, string $replace, array &$haystack ){
array_walk_recursive($haystack,
function (&$item, $key, $data){
$item = str_replace( $data['needle'], $data['replace'], $item );
return $item;
},
[ 'needle' => $needle, 'replace' => $replace ]
);
}
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
$basket = array_replace($base, $replacements);