Array key value pair from string - php

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)

Related

how to split string into an array and sort them

i am working on a module where i have stored string in a column separated by comma(,) and i have split the string into an array and added the array into drop down, but when i am doing this with multiple columns, its not sorting the array in dropdown
here is the code
$pp=DB::table('gcp_projects')->where('niche','!=',' ')->where('niche','!=','')->where('niche','!=',null)->orderBy('niche')->pluck('niche');
$testing=explode(",",$pp);
$arr=array();
$tttt=array();
for($i=0;$i<=count($pp);$i++)
{
$arr= explode(",",$pp);
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $arr);
$tttt=array_unique($temp);
sort($tttt);
}
<?php
// Use preg_split() function
$string = "123,456,78,000";
$str_arr = preg_split ("/\,/", $string);
print_r($str_arr);
// use of explode
$string = "123,46,78,000";
$str_arr = explode (",", $string);
print_r($str_arr);
?>
you can do it like this and use sort option like
$values = array ("zercggj.co.uk", "lkjhg.org.au", "qqxze.org.au",
"bfhgj.co.uk", "sdfgh.org.uk");
echo "<br>input:<br>";
foreach ($values as $host) echo "$host<br>";
// create a suitable structure
foreach ($values as $host)
{
$split = explode('.', $host, 2);
$printable[$split[1]][] = $split[0];
}
// sort by domains
asort ($printable);
// output
echo "<br>sorted:<br>";
foreach ($printable as $domain => $hosts)
{
echo "domain: $domain<br>";
// sort hosts within the current domain
asort ($hosts);
// display them
foreach ($hosts as $host)
echo "--- $host<br>";
}
So Far i found this solution which is working for me
$pp=DB::table('gcp_projects')->whereNotNull('niche')->orderBy('niche')->pluck('niche')->toArray();
$aa=implode(',',$pp);
$myArray = explode(',', $aa);
$im=implode(' ',$myArray);
$ex=explode(' ',$im);
$tttt=array_unique($ex);
sort($tttt);
$str = preg_replace("/[^a-zA-Z 0-9]+/", "", $tttt);
$result = array_filter($str);
you have to mention orderby ASC OR DESC
orderBy('created_at', 'asc') Or orderBy('created_at', 'asc')

Remove Quotes from object using php

I have a json object.In that i need to remove double quotes.
{"1":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"},"2":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"},"3":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"}}
I need to remove the Quotes from object.
{"1":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}},"2":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}},"3":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}}}
I tried :
json_decode($request),json_decode(json_encode($request))
but no result.it returns null.
Also i need to add quotes to keys
{"m":4,"preference":1,"r":0,"tt":0}
You need first to try make valid json on sender. But if you can't, use below code to manually parse source string $str
function like_json_decode($str) {
$arr = array_map('trim', explode(',', $str));
$new_arr = [];
foreach ($arr as &$x) {
$x = trim($x, ' {}');
$x = array_map('trim', explode(':', $x));
$new_arr[$x[0]] = $x[1];
}
return $new_arr;
}
$arr = json_decode($str, true);
foreach ($arr as &$subarr) {
foreach($subarr as &$x) {
$x = like_json_decode($x);
}
}
print_r($arr);
demo

extract values from srting seperated by | in php

How to extract values from string seperated by |
here is my string
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
i need to store
$foo=1478
$boo=7854
$ccc=74125
Of course every body would suggest the explode route:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
foreach(array_filter(explode('|', $var)) as $e){
list($key, $value) = explode('=', $e);
${$key} = $value;
}
Also, another would be to convert pipes to ampersand, so that it can be interpreted with parse_str:
parse_str(str_replace('|', '&', $var), $data);
extract($data);
echo $foo;
Both would produce the same. I'd stay away with variable variables though, it choose to go with arrays.
Explode the string by | and you will get the different value as array which is separated by |. Now add the $ before each value and echo them to see what you want.
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
echo "$".$val."<br/>";
}
You will get:
$foo=1478
$boo=7854
$bar=74125
$aaa=74125
$bbb=470
$ccc=74125
$ddd=1200
OR if you want to store them in the $foo variable and show only the value then do this:
$var = 'foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$arr = explode("|", $var);
$arr = array_filter($arr);
foreach($arr as $val){
$sub = explode("=", $val);
$$sub[0] = $sub[1];
}
echo $foo; //1478
You can use PHP variable variable concept to achieve your objective:
Try this:
<?php
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$vars=explode("|",$var);
foreach($vars as $key=>$value){
if(!empty($value)){
$varcol=explode("=",$value);
$varname=$varcol[0];
$varvalue=$varcol[1];
$$varname=$varvalue; //In this line we use $$ i.e. variable variable concept
}
}
echo $foo;
I hope this works for you....
You can use explode for | with array_filter to remove blank elements from array, and pass the result to array_map with a reference array.
Inside callback you need to explode again for = and store that in ref array.
there after use extract to create variables.
$var='foo=1478|boo=7854|bar=74125|aaa=74125|bbb=470|ccc=74125|ddd=1200|';
$result = array();
$x = array_map(function($arr) use(&$result) {
list($key, $value) = explode('=', $arr);
$result[$key] = $value;
return [$key => $value];
}, array_filter(explode('|', $var)));
extract($result);
Use explode function which can break your string.
$array = explode("|", $var);
print_r($array);

implode() string, but also append the glue at the end

Trying to use the implode() function to add a string at the end of each element.
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array);
print($attUsers);
Prints this:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132
How do I get implode() to also append the glue for the last element?
Expected output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
//^^^^^^^^^^^^ See here
There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:
$numbers = ['9898549130', '9898549131', '9898549132'];
$attUsers = implode(
',',
array_map(
function($number) {
return($number . '#txt.att.net');
},
$numbers
)
);
print_r($attUsers);
This seems to work, not sure its the best way to do it:
$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("#txt.att.net,", $array) . "#txt.att.net";
print($attUsers);
Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.
Input:
$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("#txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")
Output:
9898549130#txt.att.net,9898549131#txt.att.net,9898549132#txt.att.net
This was an answer from my friend that seemed to provide the simplest solution using a foreach.
$array = array ('1112223333', '4445556666', '7778889999');
// Loop over array and add "#att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
$array[$index] = $phone_number . '#att.com';
}
// join array with a comma
$attusers = implode(',',$array);
print($attusers);
$result = '';
foreach($array as $a) {
$result = $result . $a . '#txt.att.net,';
}
$result = trim($result,',');
There is a simple solution to achieve this :
$i = 1;
$c = count($array);
foreach ($array as $key => $val) {
if ($i++ == $c) {
$array[$key] .= '#txt.att.net';
}
}

php call array from string

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

Categories