Reputation: 113
I have a function like this:
function array2string($data) {
if($data == '') return '';
return addslashes(var_export($data, TRUE));
}
I invoke this function convert $_REQUEST Array to String just like
array2string($_REQUEST)
and convert the result String to Array use this function:
function string2array($data) {
// print_r($data);
$data=str_replace('\'',"'",$data);
// $data=str_replace(''',"'",$data); // add by futan 2015-04-28
$data=str_replace("\'","'",$data);
// print_r($data);exit();
if($data == "") return array();
@eval("\$array = $data;");
return $array;
}
Generally, it can work, bur sometimes,it doesn't work.
the result like this:
array ( \'name\' => \'xxx
I cant find any problem, because I cant recurrence error. someone can help me??
Upvotes: 0
Views: 57
Reputation: 1814
Another alternative besides serialize
would be to use json_encode
:
$array = ['foo' => 'bar'];
$string = json_encode($array); // $string now has {'foo': 'bar'}
// Restore array from string.
// Second parameter is passed to make sure it's array and not stdClass
$array = json_decode($string, true);
Don't invent your function unless you absolutely need to. If you think you do, please add an explanation, why, so that we can help.
Upvotes: 0
Reputation: 905
Instead of creating your own custom function to get the string representation of the array/object and vice versa, you should use the PHP native serialize() / unserialize() for that purpose:
// Serialize the array data. This string can be used to store it in the db
$serialised_string = serialize($_REQUEST);
// Get the array data back from the serialized string
$array_data = unserialize($serialised_string);
Also you could run into PHP injection issues by eval()
usage in your custom function string2array()
.
Upvotes: 3