douwei1904 2015-10-23 00:19
浏览 53

PHP:如何将不同长度的数据分成

I'm reading data from an object (OLE binary file) and need to find a way to split the data into an array or other format so I can obtain the few pieces of information I need. I'm not sure how this can be achieved.

The data comes in like this:

|some_other_delimited_data|RECORD=1|FIELD_1=A|FIELD_2=B|FIELD_3=C|RECORD=21|FIELD_1=C|FIELD_4=D|FIELD_5=E|RECORD=47|FIELD_6=F||RECORD=1|FIELD_1=G|FIELD_2=H|RECORD=37|FIELD_8=J|FIELD_9=K|FIELD_10=L|RECORD=40|FIELD_11=M|RECORD=47|FIELD_6=N|some_more_delimited_data|

Each data set starts with "RECORD=1" which contains a number of fields, followed by additional records. Each of these records (numbered 2-46) can occur multiple times and with a varying number of fields (ie RECORD=17 could occur five times and have a different number of fields for each one). The data set ends with RECORD=47 and its fields. A full set of data is contained between and including RECORD=1 and RECORD=47.

Multiple data sets exists so there are numerous "RECORD=1" to "RECORD=47" blocks that I need to get data from.

Each RECORD can have a varying number of fields.

Everything is separated by a "|" delimiter and there doesn't seem to be any other delimiters in the stream.

For each data set, I need to get:

  • From RECORD=24, the data from FIELD_1 where FIELD_2="FOO"
  • From RECORD=31, the data from FIELD_1 where FIELD_2="BAR"

How can this be done? I have multiple files that data needs to be pulled from each containing multiple data sets so it needs to be fairly efficient.

  • 写回答

1条回答 默认 最新

  • drq22639 2015-10-23 01:41
    关注

    Here is an idea to split the string:

    $stream = "|some_other_delimited_data|RECORD=1|FIELD_1=A|FIELD_2=B|FIELD_3=C|RECORD=21|FIELD_1=C|FIELD_4=D|FIELD_5=E|RECORD=47|FIELD_6=F||RECORD=1|FIELD_1=G|FIELD_2=H|RECORD=37|FIELD_8=J|FIELD_9=K|FIELD_10=L|RECORD=40|FIELD_11=M|RECORD=47|FIELD_6=N|some_more_delimited_data|";
    
    $matches = array();
    preg_match_all ("/RECORD=([0-9]+)((\|FIELD_[0-9]+=[A-Z]+)+)/", $stream, $matches, PREG_SET_ORDER);
    
    $array = array();
    foreach ($matches as $match) {
        $submatches = array();
        preg_match_all ("/\|FIELD_([0-9]+)=([A-Z]+)/", $match[2], $submatches, PREG_SET_ORDER);
        $fields = array();
        foreach($submatches as $submatch) {
            $fields[$submatch[1]] = $submatch[2];
        }
        $array[] = array('record' => $match[1], 'fields' => $fields);
    }
    
    print_r($array);
    

    Extracting the desired values from the array should be easy now, use array_keys(), array_search() and array_column().

    评论

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件