mysql value in array format, convert to PHP array - php

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.

Related

Decoding text in PHP not decode

So. I have three massive texts from WYSIWYG editor that I need to store in DB (MySQL). To do that I use PHP function rawurlencode() put them in one array and serialize() the array, then insert into DB. But the problem is when I need to rawurldecode().
First I unserialize() then text decodes normally, but image tag decodes like this:
`<img alt="\"\"" src="\"/ckfinder/userfiles/images/facebook.PNG\""
style="\"float:right;" height:200px; width:198px\">`
there is multiple these ->\" that I dont need and in fact they don't appear in code that is not encoded. str_replace() won't help.
Maybe I do something wrong and there is better way how to store long texts in serialized array?
Use the stripcslashes() function available by default in PHP.
It will remove the backslashes that are added as escape characters.
Example

Modify each "segment" of string in PHP

For example I have string en/something1/something2 and I need to modify something in each segment.
Solution obviously is explode string with delimiter "/", modify each element and implode back. But I am fairly sure there is shorter way to do it.

PHP key=value string to array

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.

Make Json parsable by php

I have some weirdly formatted json string which is invalid json, but executes as valid javascript. This means PHP json_decode, will not work.
{
"Devices":{
"Device1":"{ \"Name\"=\>\"AutoTap LDVDS\",\"ID\"=\>\"LDVDSDevice\"}"
}
}
The backslashes are not valid. Is there some way I can escape this string so it can be re-encoded exactly the same as it came in?
Edit I don't care about parsing the messy string at all. It's preventing me from accessing other data. I was doing a simple regex to strip the ugly strings out of the json before parsing it. But now I need to re-encode the result array back into JSON and I want to avoid losing this data. The ugly string should remain exactly the same, as it may be important to some other application that uses this data.
The => comes from ruby object notation in case you are wondering.
Well, it's those weird escaped > that are killing it: \>
I see no reason why you can't str_replace them out of existence safely with a simple:
<?php
$code='{
"Devices":{
"Device1":"{ \"Name\"=\>\"AutoTap LDVDS\",\"ID\"=\>\"LDVDSDevice\"}"
}
}';
$code=str_replace('\\>','>',$code);
var_export(json_decode($code));
But then, you know the domain of your data.
And you should apply a grain of salt before applying that blindly to all your inputs.
You could run stripslashes on it, and then pass that sring into json_decode.

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.

Categories