-3

Unfortunately the array is saved in database as string

'Array
(
    [MerID] => 00000
    [AcqID] => 2121
    [OrderID] => 94
    [ResponseCode] => 1
    [ReasonCode] => 1

)'

I want this string to be converted to array as original.Please Help

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Rex Rex
  • 1,030
  • 1
  • 8
  • 29
  • 3
    Ask yourself why you need to save it like `'array(1,2,3)'` – Daan Jul 27 '15 at 11:24
  • ok.is there any way to convert this? – Rex Rex Jul 27 '15 at 11:25
  • Use [substr()](http://www.php.net/manual/en/function.substr.php) to convert `array(1,2,3)` to `1,2,3`, then [explode()](http://www.php.net/manual/en/function.explode.php) on `,`.... but you shouldn't really be storing data like this in the first place – Mark Baker Jul 27 '15 at 11:26
  • $res = var_export($array, true); or implode/explode – Konstantin Jul 27 '15 at 11:27
  • http://php.net/manual/ru/function.eval.php – Konstantin Jul 27 '15 at 11:33
  • possible duplicate of [How create an array from the output of an array printed with print\_r?](http://stackoverflow.com/questions/7025909/how-create-an-array-from-the-output-of-an-array-printed-with-print-r) – splash58 Jul 27 '15 at 11:37
  • possible duplicate of [how to read output of var\_export into a variable in PHP?](http://stackoverflow.com/questions/933506/how-to-read-output-of-var-export-into-a-variable-in-php) – ghoti Jul 27 '15 at 15:20

1 Answers1

0

As others have warned you it is a horrible idea to store data you actually need to use in this format (is that from a var_dump?). If you're already stuck with data in this format, this will work for the given string:

$string = ('Array
(
    [MerID] => 00000
    [AcqID] => 2121
    [OrderID] => 94
    [ResponseCode] => 1
    [ReasonCode] => 1

)');

$arrayOnly = preg_match('!\(([^\)]+)\)!', $string, $match);
$prepared = '$array = array(' . str_replace(['[', ']', "\n"], ['"','"', ","], trim($match[1])) . ');';
 eval($prepared); //$array is now set to your array

Keep in mind this your mileage may vary, this works for this specific instance but may fail on multidimensional array strings.

If you do have control of how the data is actually stored and want a flexible array storage solution, look to either json_encode or serialize the array prior to storing. Then when you retrieve the data, you can json_decode or unserialize to get the original array.

user1842104
  • 181
  • 5