Remove Quotes from object using php - 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

Related

Array key value pair from string

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)

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';
}
}

Convert array of delimited strings to variables

I need to convert all items in array to variables like:
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
And I want to convert it to this:
$apple = 5;
$banana = 7;
$orange = 8;
Like normal variables. Is it possible?
Seems like a silly thing to do, why not convert it into an associative array? But if you must:
foreach($item as $x) {
list($name, $val) = explode('=', $x, 2);
$$name = $val;
}
You can try to join the array and parse the string into variables
parse_str(implode('&',$item));
You can do it like this
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
foreach($item as $row)
{
$new = explode('=',$row);
$array[$new[0]] = $new[1];
}
extract($array);
echo $apple;
echo $banana;
echo $orange;
Your array looks like someone exploded an ini file on its newlines.
Implode with newlines, then parse, then call extract() to generate the variables. (Demo)
extract(
parse_ini_string(
implode(PHP_EOL, $item)
)
);
echo "$apple $banana $orange";
Using explode() or parse_ini_string() or preg_ functions (etc.) will render the numeric values as string-type.
If you'd like the numeric values to be integer-typed, then using %d in the "format" parameter of sscanf() will be most direct. (Demo1)
foreach ($item as $string) {
[$key, $$key] = sscanf($string, '%[^=]=%d');
}
Generally speaking, I do not advise the generation of individual variable (I more strenuously advise against variable variables). Perhaps an associative array would be suitable. (Demo)
$result = [];
foreach ($item as $string) {
[$key, $result[$key]] = sscanf($string, '%[^=]=%d');
}
var_dump($result);

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