Oct 5 2007

Implementarea functiei PHP serialize() in JavaScript

[js]
/**
*function implementing PHP’s serialize() function
*@param: v – elements to be serialized
*@return: serialized string
*/
function serialize(v){
if(typeof(v)==’object’ && v.constructor==Array){
var i,s=”,c=0;
for(i in v){
++c;
s+=serialize(i)+serialize(v[i]);
}
s=”a:”+c+”:{“+s+”}”;
return s;
} else {
if(Number(v)==v){
return ‘i:’+v+’;’;
} else
if(typeof(v)==’string’){
return ‘s:’+v.length+’:”‘+v+'”;’;
}
}
}
[/js]


Oct 5 2007

Implementarea functiei PHP print_r() in JavaScript

[js]
/**
*function : print_r()
*@param: array-array,hass or object
*@param: level – OPTIONAL
*@returns: string – The textual representation of the array.
*/
function print_r(array,level) {
var dumped_text = “”;
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = ” “;
for(var j=0;j if(typeof(array) == ‘object’) { //Array/Hashes/Objects
var obj = 0;
for(var item in array) {
var value = array[item];
if(typeof(value) == ‘object’) { //If it is an array,
dumped_text += level_padding + “[” + item + “] => Array\n ” + level_padding + “( \n”;
dumped_text += print_r(value,level+1);
dumped_text += level_padding + “)\n”;
} else {
dumped_text += level_padding + level_padding + “[” + item + “] => ” + value + “\n”;
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = “===>”+array+”<===(“+typeof(array)+”)”;
}
return dumped_text;
}
/**
*call of function
*/
alert (print_r (MyArray));
[/js]


Oct 5 2007

Implementarea functiei PHP in_array() in JavaScript

[js]
/**
*functin implementing PHP’s in_array() function
*@param: array – search array
*@param: search_term – element to be searched
*@return: true/false
*/
function in_array (array, search_term) {
if (array) { //see if array exists
var i = array.length;
if (i > 0) {
do {
if (array[i] === search_term) {
return true;
}
} while (i–);
}
return false;
} else {
return false;
}
}
[/js]