困难的数据检索和爆炸

时间:2015-07-26 04:03:19

标签: php arrays explode

我的朋友和我正在研究一些小型的网络和桌面应用程序,目前我们正在尝试实施统计选项来分析哪些应用程序最常用等等。因为他发送了一个POST请求,应该看起来像这样:

---------- website_application1 ---------- 
time_usage: 2h
other_info: XYZ
----------website_application1_end----------
---------- website_application2 ---------- 
time_usage: 2h
other_info: XYZ
data without key
----------website_application2_end----------

所以我想将数据提取并分解为以下

Array
(
    [website_application1] => array('time_usage'=> '2h','other_info'=>'XYZ');
    [website_application2] => array('time_usage'=> '2h','other_info'=>'XYZ','keyless'=>'data without key');
)

所以delims之间的每一行。使用键进入数组元素。在块结束时,可能存在一些没有密钥的数据,因此可以使用“:”来爆炸。到目前为止,我只设法在开始和结束delim之间提取数据。但是没有给数组键命名等等我猜对了如何正确处理这个问题。 Thx提前任何帮助

2 个答案:

答案 0 :(得分:2)

正如我所说,我会重构

<website_application1>
    <time_usage>2h</time_usage>
    <other_info>XYZ</other_info>
</website_application1>
<website_application2>
    <time_usage>2h</time_usage>
    <other_info>XYZ</other_info>
data without key -- what is this <data_without_key/>
<website_application2>


{
    website_application1:{
        time_usage: 2h
        other_info: XYZ
    }
    website_application2:{
        time_usage: 2h
        other_info: XYZ
        data without key: true
    }
}

当然,您可以编写一些PHP来解析它,但将来会有多强大。

即使你发布的是一个很好的例子

---------- website_application2 ---------- 
time_usage: 2h
other_info: XYZ
data without key
----------website_application2_end----------
你知道吗?

---------- website_application2 ---------- 
----------website_application2_end----------

现在--web vs -- web怎么样,不一致会让你试图解析它。这更明显

other_info: XYZ
data without key

如果稍后您将data without key更改为data_without_key:truedata_without_key: truedata_without_key : true,该怎么办?维持这将是一个烂摊子。我们听到RESTSOAPAJAX等内容是有原因的。有标准,因为它们是一致的。

对于实现和检查边缘情况所花费的时间,您可以非常轻松地使用其中一个标准。如果没有,你进入数据抓取的领域,那就是艺术和运气,然后是科学。

当然可以做(伪代码)

while fread($line)
if preg_match( '/website_(?P<application>[^-]+)/', $line, $match )
then check each line - explode by : trim white space and build an array
etc...

答案 1 :(得分:1)

虽然重构使用更好的数据格式可能是最佳解决方案,正如其他人已经指出的那样,如果这不是一个选项,你可以尝试逐行抓取文本并像构建你的数组一样这样:

<?php

$testData =<<<TXT
---------- website_application1 ----------
time_usage: 2h
other_info: XYZ
----------website_application1_end----------
---------- website_application2 ----------
time_usage: 2h
other_info: XYZ
data without key
----------website_application2_end----------
TXT;

$testDataArray = explode("\n", $testData);

while(list(,$line)=each($testDataArray)) {
    if($line[0]=="-"){
        list(,$key) = preg_split("/----------/",$line);
    }else{
        $usageLineArray = preg_split("/:/",$line);
        if(count($usageLineArray)>1) {
            $parsedArray[trim($key)][$usageLineArray[0]] = $usageLineArray[1];
        }else{
            $parsedArray[trim($key)]["keyless"] = $usageLineArray[0];
        }
    }
}

print_r($parsedArray);