I am storing some data in my database in a comma based string like this:
value1, value2, value3, value4 etc...
This is the variables for the string:
$data["subscribers"];
I have a function which on users request can remove their value from the string or add it.
This is how I remove it:
/* Remove value from comma seperated string */
function removeFromString($str, $item) {
$parts = explode(',', $str);
while(($i = array_search($item, $parts)) !== false) {
unset($parts[$i]);
}
return implode(',', $parts);
}
$newString = removeFromString($existArr, $userdata["id"]);
So in the above example, I am removing the $userdata['id'] from the string (if it exists).
My problem is.. how can I add a value to the comma based string?
Best performance for me
function addItem($str, $item) {
return ($str != '' ? $str.',' : '').$item;
}
You can use $array[] = $var; simply do:
function addtoString($str, $item) {
$parts = explode(',', $str);
$parts[] = $item;
return implode(',', $parts);
}
$newString = addtoString($existArr, $userdata["id"]);
function addToString($str, $item) {
$parts = explode(',', $str);
array_push($parts, $str);
return implode(',', $parts);
}
$newString = addToString($existArr, $userdata["id"]);
Related
I have a string
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
Need to convert this string in below format.
$utmcsr = google;
$utmcmd= organic;
$utmccn= (not set);
$utmctr= (not provided);
and more can come. I have try explode and slip function but not gives result. Please suggest.
Thanks in advance
With "Double explode" you can extract all key-value pairs from the string. First, explode on the pipe symbol, the resuting array contains strings like utmcsr=google. Iterate over this array and explode each string on the equal sign:
$result = [];
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$arr = explode('|', $str);
foreach($arr as $str2) {
$values = explode('=', $str2);
$result[ $values[0] ] = $values[1];
}
Try this one
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$new_array = explode('|', $str);
$result_array = array();
foreach ($new_array as $value) {
$new_arr = explode('=', $value);
$result_array[$new_arr[0]] = $new_arr[1];
}
extract($result_array);
echo $utmcsr;
echo $utmctr;
Output: google(not provided)
I am getting the following data from a file_get_contents php://input
transfer_date:2018-02-14 content:1000_102eabca374092d1e97daf0bf52e9d count:1
transfer_date:2018-02-13 content:1000_1022e2297c8e9e1a18743182e4f265 count:0
transfer_date:2018-02-13 content:1000_10254e35fda57121d48bd71693c500 count:0.5
transfer_date:2018-02-12 content:102ead3122a4c8742bff97fcc46b38 count:0.5
transfer_date:2018-02-12 content:1000_102ee58d8e12eadbce86d526607164 count:0.5
Any ideas on how to turn this into a json array?
I want the data in format
"transfer_date":"2018-02-14","content":"123445585989898","count":"1"
so I can run it through a for each.
I have tried on the values but it only gets me halfway there and I can keep using find replace but there must be another way no?:
//$datatwo = str_replace('transfer_date: '"transfer_date":"',"$datatwo");
You can use regex to get not-space symbols before and after colon
$arr = array_map(function($x) {
if (preg_match_all('/(\S+):(\S+)/',$x, $m)) {
return array_combine($m[1], $m[2]);
}
}, file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
echo json_encode($arr, JSON_PRETTY_PRINT);
demo
i'm not sure, but i guess this would work for you.
<?php
$input = file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$transfers = [];
foreach($input as $line) {
$transfer=[];
// break the white space between key=value so each key/value get added alone
$parts = explode(' ',$line);
foreach($parts as $part) {
// separate the key and value
$values=explode(':',$part);
$transfer[ $values[0] ] = $values[1] ?? null;
}
// add to the result
$transfers[]= $transfer;
}
// print json encoded result
echo json_encode($transfers);
Simpliest you could do if the there are only spaces between fields and colons as key/value separator:
$data = ''; //your data
$data = str_replace("\r\n", "\n", $data); //remove carriage return
$lines = array_filter(explode("\n", $data)); //split your data by new line and filter empty lines
$rows = [];
foreach ($lines as $line) {
$fields = explode(' ', $line); //explode the content of a line by space to get all fields
foreach ($fields as $field) {
$fieldParts = explode(':', $field); //explode a field to get key and value
$rows[$fieldParts[0]] = $fieldParts[1]; //assign it to your result array
}
}
var_dump(json_encode($rows));
I've come up with this monstrosity :
echo $value;
And the result is this:
"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"
This is i a string....but i want to make it look like this in end.
$value= array("_aaaaaaa","_bbbbbb","_cccccc","_dddddd");
I've tried everything.How can i make this string into an array like the above ?
Any help here ?
-Thanks
If I understand you correctly, $value = explode(',', $value); should turn this into an array.
Try as following:
$value= '"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"';
$array = array_map(function($v) { return trim($v, '"'); }, explode(',', $value));
More simply:
$array = explode('","', trim($value, '"'));
Hope this help
$str = '"_aaaaaaa","_bbbbbb","_cccccc","_dddddd"';
$value = explode(',', $str);
foreach ($values as $val) {
$val = trim($val, '"');
}
Your question would need more specific description I guess what you are trying to achieve but if you have a string that contains values separated by , and surrounded with quotes then you want to do something like this:
$value = explode(',', $value);
foreach ($value as &$val) {
$val = trim($val, '"');
}
I have a string that looks like this "thing aaaa" and I'm using explode() to split the string into an array containing all the words that are separated by space. I execute something like this explode (" ", $string) .
I'm not sure why but the result is : ["thing","","","","aaaa"]; Does anyone have an idea why I get the three empty arrays in there ?
EDIT : This is the function that I'm using that in :
public function query_databases() {
$arguments_count = func_num_args();
$status = [];
$results = [];
$split =[];
if ($arguments_count > 0) {
$arguments = func_get_args();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arguments));
foreach ($iterator as $key => $value) {
array_push($results, trim($value));
}
unset($value);
$filtered = $this->array_unique_values($results, "String");
foreach ($filtered as $key => $string) {
if (preg_match('/\s/',$string)) {
array_push($split, preg_split("/\s/", $string));
} else {
array_push($split, $string);
}
}
unset($string);
echo "Terms : ".json_encode($split)."<br>";
foreach ($filtered as $database) {
echo "Terms : ".json_encode()."<br>";
$_action = $this->get_database($database);
echo "Action : ".json_encode($_action)."<br>";
}
unset($database);
} else {
return "[ Databases | Query Databases [ Missing Arguments ] ]";
}
}
It might be something else that messes up the result ?!
If you are looking to create an array by spaces, you might want to consider preg_split:
preg_split("/\s+/","thing aaaa");
which gives you array ("thing","aaaa");
Taken from here.
try this:
$str = str_replace(" ", ",", $string);
explode(",",$str);
This way you can see if it is just the whitespace giving you the problem if you output 4 commas, it's because you have 4 whitespaces.
As #Barmar said, my trim() just removes all the space before and after the words, so that is why I had more values in the array than I should have had.
I found that this little snippet : preg_replace( '/\s+/', ' ', $value ) ; replacing my trim() would fix it :)
I have a string that contains elements from array.
$str = '[some][string]';
$array = array();
How can I get the value of $array['some']['string'] using $str?
This will work for any number of keys:
$keys = explode('][', substr($str, 1, -1));
$value = $array;
foreach($keys as $key)
$value = $value[$key];
echo $value
You can do so by using eval, don't know if your comfortable with it:
$array['some']['string'] = 'test';
$str = '[some][string]';
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));
$value = eval($code);
echo $value; # test
However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.
Another example if you need to write access to the array item, you can do the following:
$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
$value = &$value[$segment];
}
echo $value;
$value = 'changed';
print_r($array);
This is actually the same principle as in Eric's answer but referencing the variable.
// trim the start and end brackets
$str = trim($str, '[]');
// explode the keys into an array
$keys = explode('][', $str);
// reference the array using the stored keys
$value = $array[$keys[0][$keys[1]];
I think regexp should do the trick better:
$array['some']['string'] = 'test';
$str = '[some][string]';
if (preg_match('/\[(?<key1>\w+)\]\[(?<key2>\w+)\]/', $str, $keys))
{
if (isset($array[$keys['key1']][$keys['key2']]))
echo $array[$keys['key1']][$keys['key2']]; // do what you need
}
But I would think twice before dealing with arrays your way :D