note 64128 added to ref.array
| From: | KevinLaw at osu1 dot php dot net | Date: | Sat, 08 Apr 2006 05:38:23 +0000 |
| Subject: | note 64128 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-107552@lists.php.net to get a copy of this message | ||
To convert a well formatted string into an array or vice versa. I use it to write an array to file.
/* To parse a string in specific format to array
eg.
parse_array("A:abc,B:bcd,C:(C1:cv1,C2:(C21:cv21)),D:dfg");
return array:
Array (
[A] => abc
[B] => bcd
[C] => Array (
[C1] => cv1
[C2] => Array (
[C21] => cv21
)
)
[D] => dfg
)
*/
function parse_array($line){
$q_pos = strpos($line, ":");
$name = substr($line,0,$q_pos);
$line = trim(substr($line,$q_pos+1));
$open_backet_pos = strpos($line, "(");
if($open_backet_pos===false || $open_backet_pos>0){
$comma_pos = strpos($line, ",");
if($comma_pos===false){
$result[$name] = $line;
$line = "";
}else{
$result[$name] = substr($line,0,$comma_pos);
$result = array_merge($result, parse_array(substr($line,$comma_pos+1)));
$line = "";
}
}else if ($open_backet_pos==0){
$line = substr($line,1);
$num_backet = 1;
$line_char_array = str_split($line);
for($index = 0; count($line_char_array); $index++){
if($line_char_array[$index] == '('){
$num_backet++;
}else if ($line_char_array[$index] == ')'){
$num_backet--;
}
if($num_backet == 0){
break;
}
}
$sub_line = substr($line,0,$index);
$result[$name] = parse_array($sub_line);
$line = substr($line,$index+2);
}
if(strlen($line)!=0){
$result = array_merge($result, parse_array($line));
}
return $result;
}
/* To parse an array into a single line
eg.
parse_array(array);
if array is :
Array (
[A] => abc
[B] => bcd
[C] => Array (
[C1] => cv1
[C2] => Array (
[C21] => cv21
)
)
[D] => dfg
)
result string is : "A:abc,B:bcd,C:(C1:cv1,C2:(C21:cv21)),D:dfg"
*/
function parse_line($array){
$line = "";
foreach($array AS $key => $value){
if(is_array($value)){
$value = "(". parse_line($value) . ")";
}
$line = $line . "," . $key . ":" . $value . "";
}
$line = substr($line, 1);
return $line;
}
----
Server IP: 202.181.244.117
Probable Submitter: 203.218.175.51
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/note/edit/64128
Del: integrated -- http://master.php.net/note/delete/64128/integrated
Del: useless -- http://master.php.net/note/delete/64128/useless
Del: bad code -- http://master.php.net/note/delete/64128/bad+code
Del: spam -- http://master.php.net/note/delete/64128/spam
Del: non-english -- http://master.php.net/note/delete/64128/non-english
Del: in docs -- http://master.php.net/note/delete/64128/in+docs
Del: other reasons-- http://master.php.net/note/delete/64128
Reject -- http://master.php.net/note/reject/64128
Search -- http://master.php.net/manage/user-notes.php