2012-12-19 76 views
1

我有以下的PHP数组:阵列循环和取消

$data = Array 
( 
    [rules1.txt] => Array 
    ( 
     [rules] => Array 
     ( 
      [0] => throw rule blah 
      [1] => punt rule blah 
      [2] => #comment 
      [3] => 
      [4] => #punt rule that is commented out 
     ) 
     [item] => rules1 
     [itemId] => 4 
     [new] => true 
    ) 

    [rules2.txt] => Array 
    (
     ... 
    ) 

    ... 
) 

数组我很担心的部分是$数据[“规则”]和其键和值。阵列的这一部分具有不同数量的键,当然,这些值也是不同的。我试图做的是“找到”以特定关键字开头的值,例如'throw'或'punt'...空白行(如$ data ['rules'] [3] )和注释值(如$ data ['rules'] [2]和... [4])需要删除。

在任何循环(一个或多个)我最终使用我需要一个结构是怎样的,结束了

所以......

$data = Array 
( 
    [rules1.txt] => Array 
    ( 
     [rules] => Array 
     ( 
      [0] => throw rule blah 
      [1] => punt rule blah 
     ) 
     [item] => rules1 
     [itemId] => 4 
     [new] => true 
    ) 

    [rules2.txt] => Array 
    (
     ... 
    ) 

    ... 
) 

在我的努力实现我的目标,我创建了一个简单的,额外的阵列持关键字...

$actions = Array(
    'throw', 
    'punt' 
); 

...在循环创建第三个数组,看起来像使用...

$removeThese = Array 
( 
    [rules1.txt] => Array 
    ( 
     [0] => 2 
     [1] => 3 
     [2] => 4 
    ) 

    [rules2.txt] => Array 
    (
     ... 
    ) 

    ... 
) 

上面的数组$ removeThese只是保存每个文件(rules1.txt,rules2.txt等)需要从$ data ['rules']中删除的$ data ['rules']索引。

由于我用PHP在耳朵后面湿了,我在每次尝试的方法都失败了。正确的数据不是未设置()或创建$ removeThese时我错误地覆盖我的数组。

寻找建议,最好从A点(带有要移除的项目的原始$数据)到B点(更新的$日期,删除项目)。

非常感谢。

编辑

尝试下面的代码,这似乎是接近,但$ removeThese被覆盖......只有从$最后的文件数据和$数据[“规则”]上次指数结束了。

foreach ($data as $fileName => $fileData) 
{ 
    foreach ($fileData as $fdKey => $fdValue) 
    { 
     if ($fdKey === 'rules') 
     { 
      foreach ($fdValue as $key => $value) 
      { 
       foreach ($actions as $action) 
       { 
        if (strpos($value, $action) != 0) 
        { 
         if (!in_array($value, $removeThese[$fileName])) 
         { 
          $removeThese[$fileName][] = $key; 
         } 
        } 
       } 
      } 
     } 
    } 
} 

所以我看到两个问题:

1)我在哪里出了错造成$ removeThese被覆盖?
2)什么是更好的书写方式?

固定

我一直在寻找,我不认为这是太糟糕了最后的代码 - 虽然我有很多东西需要学习......

foreach ($data as $fileName => $fileData) 
{ 
    foreach ($fileData as $fdKey => $fdValue) 
    { 
     if ($fdKey === 'rules') 
     { 
      foreach ($fdValue as $key => $value) 
      { 
       $value = rtrim($value, "\n"); 

       if (!in_array($value, $actions) === true) 
       { 
        unset($data[$fileName][$fdKey][$key]); 
       } 
      } 
     } 
    } 
} 

一大堆试验和错误,但唉,它的作品!我相信很多人都可以做得更好,速度更快。希望我能加快速度。

现在我该如何投票自己的工作并接受我自己的解决方案?

回答

1

我建议使用array_filter()。首先要承认的值函数忽略:

function shouldIgnore($value) { 
    return !in_array($value, array('throw', 'punt')); 
} 

然后过滤这样的:

$data["rules1.txt"]["rules"] = array_filter($data["rules1.txt"]["rules"], "shouldIgnore"); 
+0

在我的努力是彻底和解决方案,我认为真正传达灵活性,什么应该被输送丢失了。我相信这可以通过对$ data进行简单的foreach()循环并在合适的地方执行unset()来完成。根据检查的内容,strpos()返回false或其他地方的适当位置。另一种选择可能会结合array_search ...只是想知道我正在努力的是什么。 – user1801810

+0

哦,我想我把它纳入第二个foreach()我在我上面的更新/编辑。 – user1801810