note 47636 added to function.array
| From: | mwwaygooAThotmailDOTcom at osu1 dot php dot net | Date: | Tue, 23 Nov 2004 17:00:49 +0000 |
| Subject: | note 47636 added to function.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-80932@lists.php.net to get a copy of this message | ||
I have had some problems with unserializing a standard single dimensional array. On some it will
work fin, but others will fail, and always the same ones. SO I decided to write an unarray function
which will do the reverse of the array function.
e.g.
$my_array=array(1,1,1,1);
print_r($my_array) would give
Array(
[0] => 1,
[1] => 1,
[2] => 1,
[3] => 1
)
The object of unarray was to pass $my_array to it and get back the text creator of array(1,1,1,1);
I could then use this text an a second location to reconstruct the array. (sent via email)
<?php
function unarray2($array)
{
$text="";
if(is_array($array))
{
$text.="array(";
while(list($key,$value)=each($array))
{
if(is_array($array[$key]))
{
$text.=unarray2($array[$key])." ";
}
else
{
if(is_int($key))
{
$text.=$key;
}
else
{
$text.="'".$key."'";
}
$text.="=>";
if( (is_int($array[$key])) || (is_float($array[$key])) )
{
$text.=$array[$key].",";
}
else
{
if(is_null($array[$key]))
{
$text.="NULL,";
}
if(is_numeric($array[$key]))
{
$text.=$array[$key].",";
}
if(is_bool($array[$key]))
{
if($array[$key])
{
$text.="TRUE,";
}
else
{
$text.="FALSE,";
}
}
if(is_string($array[$key]))
{
$text.="'".addslashes($array[$key])."',";
}
}
}
}
$text.="),";
}
else
{
$text.="'".addslashes($array)."' ";
}
return $text;
}
function unarray($array)
{
return substr(unarray2($array),0,-1).";";
}
$array=array("text",array("text","text2"),
"var"=>"text3","x"=>NULL, "y"=>TRUE,
"z"=>FALSE);
$text=unarray($array);
// use the text to create a second array
eval('$new_array='.$text);
?>
It should deal with most arrays of any depth, but not objects or resources.
----
Manual Page -- http://www.php.net/manual/en/function.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47636
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47636&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47636&report=yes
Search -- http://master.php.net/manage/user-notes.php