One of my favorite things about PHP are the useful built in functions. One set of useful functions is explode and implode.
Explode takes two parameters: a string delimeter and a string to work on. It returns an array of the pieces between the delimeters.
Implode takes two parameters: a string glue and an array. It returns a string of every array element with the string glue in between.
You can do lots of interesting things with these two functions, like create csv files (even though PHP has a function specifically for that), create SQL statements using ‘,’ as glue, or in this case create a cheap data structure. By cheap data structure, I mean data that is easy to create and parse as a structured string. It is definitely not something that should be used on a large scale, but much more suitable for quick experiments.
In this case I needed to send back an unknown number of ids and usernames in a single parameter from Javascript to PHP. I created the string in Javascript like so:
// userArr is an array of arrays of the form (id,username)
var size = userArr.length;
var retStr = "";
for(i=0;i<size;i++){
retStr += userArr[i][id]+":"+userArr[i][name]+",";
}
// remove trailing comma
retStr = retStr.substring(0,retStr.length-1);
// send retStr
// ...
This creates a string like this:
1:homer,2:marge,3:bart,4:lisa,5:maggie
which is sent as a parameter, in this case the post parameter user_list. When it is received by the PHP page it is parsed like this:
$user_list = $_POST['user_list'];
$user_array = explode(",", $user_list);
$size= count($user_array);
for($i=0;$i<$size;$i++){
list($id,$name) = explode(":", $user_array[$i]);
$user_array[$i]['id'] = $id;
$user_array[$i]['name'] = $name;
}
You can now do whatever you want with this data in PHP. This technique can be very flexible, and with a creative use of delimeters, you could create very complex data structures. But then again, there’s always JSON.
Recent Comments