dqrzot2791 2015-07-27 11:23
浏览 139

将字符串数组转换为数组

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

  • 写回答

1条回答 默认 最新

  • douhunkuang8955 2015-07-27 15:02
    关注

    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(['[', ']', "
    "], ['"','"', ","], 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.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c