Create an array from content in string in PHP - php

I have a string that takes multiple key values and i would like to get these value and create an array from it.
The string will be built the same way but might contain more keys or less keys. An example of a string is this
"title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'
So i need some way to to turn these keys from the string into an array that looks like this
$array['customMessage'] = [
'title' => 'this is the new title',
'msg' => 'this_is_updated',
'body' => 'this is the new body'
];

if its allways in this format
key: val, key:val
as you have showed then use explode
$str = "title:'this is the new title', msg:'this_is_updated', body:'this is the
new body text'";
foreach(explode(',', $str) as $val)
{
$item = explode(':', $val);
$array['customMessage'][trim($item[0])] = trim($item[1],"'");
}

First of all, you should always try to use an already existing format. JSON is perfect for that, for example, and PHP has already existing functions to work with that.
If that's not possible, for whatever reason, you can use the following to achive your result string:
$string = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text'";
$firstExplode = explode(',', $string);
foreach($firstExplode as $explode) {
$val = explode(':', $explode);
$arr[$val[0]] = $val[1];
}
var_dump($arr);
Output:
array(3) {
["title"]=>
string(23) "'this is the new title'"
[" msg"]=>
string(17) "'this_is_updated'"
[" body"]=>
string(27) "'this is the new body text'"
}

this is the logic
$str = "title:'this is the new title', msg:'this_is_updated', body:'this is the new body text' ";
$str1 = explode(',', $str);
$array['customMessage'] = array();
foreach ($str1 as $key => $value) {
$str2 = explode(':', $value);
$array['customMessage'][$str2[0]] = $str2[1];
}
print_r($array['customMessage']);die;

If possible, you can build the string in a JSON format and use json_decode() like this:
$json = '{
"title":"this is the new title",
"msg":"this_is_updated",
"body":"this is the new body text"
}';
$array = json_decode($json, true);
$arrayFinal = array();
$arrayFinal['customMessage'] = $array;
echo '<pre>';
print_r($arrayFinal);
echo '</pre>';
This will give the following output:
Array
(
[customMessage] => Array
(
[title] => this is the new title
[msg] => this_is_updated
[body] => this is the new body text
)
)

The string is a simple JSON object, just decode with this native function
$array = json_decode($string)

Related

PHP - Implode, Explode works sometimes, and sometimes not? [duplicate]

What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:
$aValues = array();
$url = 'http://www.example.com?aParam='.$aValues;
or how about this:
$url = 'http://www.example.com?aParam[]='.$aValues;
Ive read examples, but I find it messy:
$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';
There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.
Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125
knittl is right on about escaping. However, there's a simpler way to do this:
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));
If you want to do this with an associative array, try this instead:
PHP 5.3+ (lambda function)
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map(function($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
},
array_keys($aValues), $aValues)
);
PHP <5.3 (callback)
function urlify($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map('urlify', array_keys($aValues), $aValues));
Easiest way would be to use the serialize function.
It serializes any variable for storage or transfer. You can read about it in the php manual - serialize
The variable can be restored by using unserialize
So in the passing to the URL you use:
$url = urlencode(serialize($array))
and to restore the variable you use
$var = unserialize(urldecode($_GET['array']))
Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.
Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.
please escape your variables when outputting (urlencode).
and you can’t just print an array, you have to build your url using a loop in some way
$url = 'http://example.com/index.php?'
$first = true;
foreach($aValues as $key => $value) {
if(!$first) $url .= '&amp';
else $first = false;
$url .= 'aValues['.urlencode($key).']='.urlencode($value);
}
<?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";
$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?>
print $str . "\n";
gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";}
and
print $strenc . "\n"; gives
a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D
So if you want to pass this $array through URL to page_no_2.php,
ex:-
$url ='http://page_no_2.php?data=".$strenc."';
To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:
<?php
$strenc2= $_GET['data'];
$arr = unserialize(urldecode($strenc2));
var_dump($arr);
?>
gives
array(4) {
["a"]=>
string(8) "Thusitha"
["b"]=>
string(10) "Sumanadasa"
["c"]=>
string(6) "Lakmal"
["d"]=>
string(11) "Nanayakkara"
}
again :D
I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.
why: http://mizine.de/html/array-ueber-get-url-parameter-uebergeben/
how: https://gist.github.com/vdite/79919fa33a3e4fbf505c
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this
www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p> Send <br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
in the received page you can use:
parse_str($str, $array);
var_dump($array);
You can combine urlencoded with json_encode
Exemple:
<?php
$cars = array
(
[0] => array
(
[color] => "red",
[name] => "mustang",
[years] => 1969
),
[1] => array
(
[color] => "gray",
[name] => "audi TT",
[years] => 1998
)
)
echo "<img src='your_api_url.php?cars=" . urlencode(json_encode($cars)) . "'/>"
?>
Good luck ! 🐘
Very easy to send an array as a parameter.
User serialize function as explained below
$url = www.example.com
$array = array("a" => 1, "b" => 2, "c" => 3);
To send array as a parameter
$url?array=urlencode(serialize($array));
To get parameter in the function or other side use unserialize
$param = unserialize(urldecode($_GET['array']));
echo '<pre>';
print_r($param);
echo '</pre>';
Array
(
[a] => 1
[b] => 2
[c] => 3
)

Broke string into vars with variable position

I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));

get value from exploded string in php

I have custom cms database and get parameter from database and my result this is:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"'
but I need get param1 value or other value. I try use explode but my result this is:
$string = explode('|',$param);
result:
array (size=4)
0 => string 'param1="value1"'
1 => string 'param2="value2"'
2 => string 'param3="value3"'
3 => string 'param4="value4"'
4 => string 'param5="value4"'
I need get value this format:
$param->param1 = value1;
You also need to explode each of the substrings on =, and then map the results into an array:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = explode('|', $param);
$results = [];
foreach ($params as $element) {
list($key, $value) = explode('=', $element, 2);
$results[$key] = json_decode($value);
}
echo $results['param1']; // value1
The call to json_decode might look a bit out of place here, but it's the quickest way to convert a quoted string into a native PHP string. The additional argument to the second explode call is to limit the result to two variables, in case the value itself contains an equals sign.
Try parse_str, you can then create an object using the array
<?php
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = array();
parse_str(str_replace('|', '&', $param), $params);
$params = (object) $params;
echo $params->param1;
?>
Nice and easy with a litte regex:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$strings = explode('|', $param);
foreach ($strings as $string) {
preg_match('#param\d="(?<value>.+)"#', $string, $matches);
var_dump($matches['value']);
}
The regex #param\d="(?<value>.+)"# looks for param followed by a number then an equals, and we create a named capture group with ?<value> in the brackets.
The output from the var_dumps looks like this:
string(6) "value1"
string(6) "value2"
string(6) "value3"
string(6) "value4"
string(6) "value5"
Try it here https://3v4l.org/bomO7
When you've split the first part using '|', you can convert the rest as though it was a CSV field with '=' as the divider. This deals with quotes and other elements.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$parms = explode('|', $param );
$values = [];
foreach ( $parms as $parm ) {
list($key, $value) = str_getcsv($parm, "=");
$values[$key] = $value;
}
print_r($values);
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$param = json_decode('{"' . str_replace(['=', '|'], ['":', ',"'], $param) . '}');
print_r($param);
This is just example. Don't use it in production :)
Use the following approach:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$result = [];
foreach (explode('|', $param) as $item) {
list($k,$v) = explode('=', $item);
$result[$k] = trim($v, '"');
}
$result = (object) $result;
// as you wanted
print_r($result->param1); // value1

PHP how to extract info from json string wtihout knowing the keys

I am querying a service if a person have phone number(s) (also maybe not). I have a json string (as return value) like the following:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
I convert this string to json_decode() function.
$jd = json_decode($json);
Then I want to get the phone numbers only into an array without keys.
if($jd->found) {
$o2a = get_object_vars($json);
}
var_dump($o2a);
When I want to see what $o2a holds with var_dump() function, I get the following:
array (size=2)
'data' =>
array (size=2)
0 =>
object(stdClass)[2]
public 'tel1' => string '1219' (length=4)
1 =>
object(stdClass)[3]
public 'tel2' => string '2710' (length=4)
'found' => boolean true
I want to get only the phone numbers into an array at the end like:
$phones = array('1219', '2710');
What makes me stop doing this is that I do not know how many phone numbers one can have. Json array could consist of more or less elements.
$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found
It may vary 0-to-n, so if it was a constant number I could create that array within a loop.
Some functions without any code :)
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);
Convert it into an array and then you should be able to iterate it easily
$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
foreach($jd['data'] as $key => $val) $phones[] = $val;
}
Instead of handling with an object, use the second parameter of the json_decode function so it would returned an array.
Check if the data and found keys exist.
Since you don't know what are the keys names, you can use array_values
Demo
.
$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
$telArr = $jd['data'];
$phones = array();
foreach($telArr as $tel){
$value = array_values($tel);
$phones[] = $value[0];
}
var_dump($phones);
}
Output:
array(2) {
[0]=>
string(4) "1102"
[1]=>
string(4) "3220"
}
Well, I would try something like that:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
foreach ($jd->data as $key -> $value) {
$phones[] = $value;
}
}
Try as using in_array and simple foreach loop
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
foreach ($arr['data'] as $key => $value) {
foreach($value as $k => $v)
$result[] = $v;
}
}
print_r($result);
Fiddle

Passing arrays as url parameter

What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:
$aValues = array();
$url = 'http://www.example.com?aParam='.$aValues;
or how about this:
$url = 'http://www.example.com?aParam[]='.$aValues;
Ive read examples, but I find it messy:
$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';
There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.
Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125
knittl is right on about escaping. However, there's a simpler way to do this:
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));
If you want to do this with an associative array, try this instead:
PHP 5.3+ (lambda function)
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map(function($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
},
array_keys($aValues), $aValues)
);
PHP <5.3 (callback)
function urlify($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map('urlify', array_keys($aValues), $aValues));
Easiest way would be to use the serialize function.
It serializes any variable for storage or transfer. You can read about it in the php manual - serialize
The variable can be restored by using unserialize
So in the passing to the URL you use:
$url = urlencode(serialize($array))
and to restore the variable you use
$var = unserialize(urldecode($_GET['array']))
Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.
Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.
please escape your variables when outputting (urlencode).
and you can’t just print an array, you have to build your url using a loop in some way
$url = 'http://example.com/index.php?'
$first = true;
foreach($aValues as $key => $value) {
if(!$first) $url .= '&amp';
else $first = false;
$url .= 'aValues['.urlencode($key).']='.urlencode($value);
}
<?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";
$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?>
print $str . "\n";
gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";}
and
print $strenc . "\n"; gives
a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D
So if you want to pass this $array through URL to page_no_2.php,
ex:-
$url ='http://page_no_2.php?data=".$strenc."';
To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:
<?php
$strenc2= $_GET['data'];
$arr = unserialize(urldecode($strenc2));
var_dump($arr);
?>
gives
array(4) {
["a"]=>
string(8) "Thusitha"
["b"]=>
string(10) "Sumanadasa"
["c"]=>
string(6) "Lakmal"
["d"]=>
string(11) "Nanayakkara"
}
again :D
I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.
why: http://mizine.de/html/array-ueber-get-url-parameter-uebergeben/
how: https://gist.github.com/vdite/79919fa33a3e4fbf505c
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this
www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p> Send <br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
in the received page you can use:
parse_str($str, $array);
var_dump($array);
You can combine urlencoded with json_encode
Exemple:
<?php
$cars = array
(
[0] => array
(
[color] => "red",
[name] => "mustang",
[years] => 1969
),
[1] => array
(
[color] => "gray",
[name] => "audi TT",
[years] => 1998
)
)
echo "<img src='your_api_url.php?cars=" . urlencode(json_encode($cars)) . "'/>"
?>
Good luck ! 🐘
Very easy to send an array as a parameter.
User serialize function as explained below
$url = www.example.com
$array = array("a" => 1, "b" => 2, "c" => 3);
To send array as a parameter
$url?array=urlencode(serialize($array));
To get parameter in the function or other side use unserialize
$param = unserialize(urldecode($_GET['array']));
echo '<pre>';
print_r($param);
echo '</pre>';
Array
(
[a] => 1
[b] => 2
[c] => 3
)

Categories