-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

7
  • 3
    Ask yourself why you need to save it like 'array(1,2,3)' Commented Jul 27, 2015 at 11:24
  • ok.is there any way to convert this? Commented Jul 27, 2015 at 11:25
  • Use substr() to convert array(1,2,3) to 1,2,3, then explode() on ,.... but you shouldn't really be storing data like this in the first place Commented Jul 27, 2015 at 11:26
  • $res = var_export($array, true); or implode/explode Commented Jul 27, 2015 at 11:27
  • php.net/manual/ru/function.eval.php Commented Jul 27, 2015 at 11:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.