正则表达式使用PHP从多维数组中提取报表ID

时间:2012-10-02 22:57:48

标签: php regex multidimensional-array

这是我的问题。我们得到了一些不起作用的PHP样本,所以我一直试图用“我的裤子座位”或多或少来写这个。我的正则表达式是生锈的,我没有处理多维数组,所以这超出了我的经验范围。

我得到的是这样的数组,但我只想要报告ID,其中[1]包含单词“Export”,然后我需要将这些传递到另一个脚本,我必须做大致相同的事情获取我可以传递给我可以实际导出的另一个脚本的结果集ID。

 [0] => Array
    (
        [0] => REPORTIDXXXXXXXXXXXXXXXXXXXXXXXXXXX
        [1] => REPORT EXPORT NAME#1
        [2] => REPORT DESCRIPTION #1
        [3] => 2012-10-02T17:31:30
    )

[1] => Array
    (
        [0] => REPORTIDYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
        [1] => REPORTOTHERNAME#2
        [2] => REPORTDESCRIPTION #2
        [3] => 2012-09-28T15:15:17
    )

[2] => Array
    (
        [0] => REPORTIDZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
        [1] => REPORT EXPORT NAME#3
        [2] => REPORT DESCRIPTION #3
        [3] => 2012-09-28T14:59:17
    )

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

function get_report_ids(array $rs) {
   $results = array();
   // loop over your data structure
   foreach($rs as $key => $data) {

      // If element 1 contains EXPORT (case insensitive)
      if(stripos($data[1], 'EXPORT') !== false) {
         // regex to capture the ID from element 0
         if(preg_match('/^EXPORTID(.*)$/i', $data[0], $matches)) {
            // add the ID to the results array
            $results[] = $matches[1];
         }
      }
   }

   // if we had results then return the array, otherwise return null
   return !empty($results) ? $results : null;
}

示例返回值:

array(
  0 => 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
  1 => 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'
)