PHP key=value string to array - php

I have a string category=45&format=1 that I want to convert into a key=value array.
Does anyone know if there is a quick way of doing this without having to write a function that explode's the & and then the = * snore *

Since you're dealing with the URL query format: parse_str
parse_str('category=45&format=1', $array);
http://php.net/parse_str

If it's a query string or doesn't contain special characters you can use parse_str.

Related

mysql value in array format, convert to PHP array

I have a part of my application that takes a bunch of values in JavaScript and stores them as an array in my MySQL database. Example of what this looks like in the database:
['123431234','3463412346','235456234','2352351','45623412']
When I grab this value in PHP, I can't seem to convert it to a PHP array properly. What's the proper method to converting a value like this that by default PHP considers a string into a PHP array?
You could try explode().
Split a string by string
You can explode your string as following:
$pieces = explode("','", $mysql_string)
You will then have to clean up the array a bit yourself. You can try str_replace to clean up any stuff you don't want.
Replace all occurrences of the search string with the replacement
string
For example:
str_replace('[', '', $pieces)
Or use an array to find everything you want to replace.
Good luck!
If you still can change the way the data is stored, you could think about json_encode() and json_decode() Which converts data into a well formatted string so it can be converted back easily. If you are communicating with a javascript client anyway, this could make your life much more comfortable.

PHP Get dynamic value from string

I'm trying to get a dynamic value from a string. But nothing shows up.
ob_start();
var_dump($torrent->result['info']['pieces']);
$pieces = ob_get_clean();
$piecescorrected = explode($pieces, 'string(*)');
echo $piecescorrected;`
Whats up with this?
Edit:
Some clarification.
$pieces needs to be filter from all the other random characters after it.
Output of $pieces:
string(12620) "< ÏÚÿÊܵ䬧âW—µ-‘CÄÞ½§§¼ø0LØëÍI­×L —#c õL2“iÓ¹ý¼Bl'-“’4žþÊYï‡
Now $pieces needs to be corrected by filtering out string(12620)
But the value is dynamic so therefore I used $piecescorrected = explode($pieces, 'string(*)');
Mind the * in string(*)
As it turned out in the comments you actually wanted just the string length.
So you don't need any output buffering or explode() calls. Just use strlen() like this:
echo strlen($torrent->result['info']['pieces']);
output:
12620
This is what's up with it: explode() is looking for a literal string. It doesn't take wildcards.
If you had a string like 1,2,3,4 you could use explode(',', '1,2,3,4') to get an array of those values by splitting on comma. Here, you could split on the literal 'string' but not 'string(*)'.

Why This Query Breaks?

I have this URL-
http://localhost/app_demo/sample.php?jsonRequest={"GenInfo":{"type":"Request","appname":"XXX","appversion":"1.0.0"},"searchDish":{"userId":"295","dishName":"","est":"Pizza & Wings","location":"","type":"","priceRange":"","deviceos":"value","deviceId":"<UDID>","deviceType":"value","pageNo":"1"}}
when I hit this URL and print
print_r($_REQUEST['jsonRequest']);
string print only upto
{"GenInfo":{"type":"Request","appname":"XXX","appversion":"1.0.0"},"searchDish":{"userId":"295","dishName":"","est":"2 Pizza
I search the net but did not get the answer.What is solution for this?
please help,
thanks.
A query string is normally composed of key/value pairs, the start of a query string is the question mark (?), and then all pairs are separated with an ampersand (&). Having an ampersand in your value is like starting a new parameter.
However, this is not the right way to do this. You shouldn't put JSON in the query string.
If you really must have an ampersand in the query string, use %26 and not &amp. %26 which is the hex value for the ampersand.
You should make a POST request instead of a GET request:
Encoding collisions
URI length limit
The character "&" is the problem, because it is reserved. (is the query string params separator)
You must "urlencode" your string before use it on your GET request. So characters like & are converted. But as jValdron point it you shouldn't put JSON in the query string, but you can do it.
So you urlencode the string:
$url = 'http://localhost/app_demo/sample.php?jsonRequest=';
$jsonRequest = urlencode('{"GenInfo":{"type":"Request","appname":"XXX","appversion":"1.0.0"},"searchDish":{"userId":"295","dishName":"","est":"Pizza & Wings","location":"","type":"","priceRange":"","deviceos":"value","deviceId":"<UDID>","deviceType":"value","pageNo":"1"}}');
$url .= $jsonRequest;
And then you urldecode
print_r(urldecode($_REQUEST['jsonRequest']));
Again, you shouldn't put JSON in the query string.

php string manipulation nonrandom sort

I am trying to sort a 4 character string thats being feed in from a user into a different order. an example might be they type "abcd" which I then take and turn it into "bcad".
Here is an example of my attempt which is not working :P
<?php
$mixedDate = $_REQUEST['userDate'];
$formatted_date = firstSubString($mixedDate,2).secondSubString($mixedDate,3).thirdSubString($mixedDate,1).fourthSubString($mixedDate,4);
//... maybe some other stuff here then echo formatted_date
?>
any help would be appreciated.
Copied from comment:
You could pretty simply do this by doing something like:
$formatted_date = $mixedDate[1].$mixedDate[2].$mixedDate[0].$mixedDate[3];
That way, you don't have to bother with calling a substring method many times, since you're just moving individual characters around.
<?php
$mixedDate = $_REQUEST['userDate'];
$formatted_date = $mixedDate{1}.$mixedDate{2}.$mixedDate{0}.$mixedDate{3};
echo $formatted_date;
?>
The curly syntax allows you to get just that one character from your string.
It should be noted that this works correctly on your sample string, abcd and turns it into bcad if $_REQUEST['userDate'] is abcd.
Look into split() in php. It takes a string and a delimiter then splits the string into an array. Either force the user to use a certain format or use a regex on the input string to put the date into a known format, like dd/mm/yyyy or dd-mm-yyyy, then use the hyphen or / as the delimiter.
Once the string is split into an array, you can rearrange it any way you like.
That is very simple.
If
$mixedDate = 21-12-2010
then, try this
echo substr($mixedDate, 3,
2).'-'.substr($mixedDate, 0,
2).'-'.substr($mixedDate, 6);
this will result in
12-21-2010
This is assuming the format is fixed.
Use str_split() to break the string into single characters:
$char_array = str_split($input_string);
If you know exactly what order you want, and you only have four characters, then from here you can actually just do it the way you wanted from your question, and concatenate the array elements back into a single string, like so:
$output_string = $char_array[2].$char_array[3].$char_array[1].$char_array[4];
If your needs are more complex, you can sort and implode the string:
Use sort() to put the characters into order:
sort($char_array);
Or one of the other related sorting functions that PHP provides if you need a different sort order. If you need an sort order which is specific to your requirements, you can use usort(), which allows you to write a function which defines how the sorting works.
Then re-join the characters into a single string using implode():
$output_string = implode($char_array);
Hope that helps.

regex to get $_GET variables

I have a URL string and would like to extract parts of the URL. I have been trying to do understand how to do it with regex but no luck.
http://www.example.com?id=example.id&v=other.variable
From the example above I would like to extract the id value ie. example.id
I'm assuming you're not referring to actual $_GET variables, but to a string containing a URL with a query string.
PHP has built-in functions to process those:
parse_url() to extract the query string from a URL
parse_str() to split the query string into its components
No need for regexp here, just use php built in function parse_url
$url = 'http://www.example.com?id=example.id&v=other.variable';
parse_str(parse_url($url, PHP_URL_QUERY), $vars);

Categories