0

我有一个数组,其中包含来自 MySQL 数据库的某些单词,这些单词与一行文本中的单词匹配。比如说,文本有 20 行长。该数组还存储了每个单词在数据库中的位置,其中一些单词与数据库中的其他单词“相关”,这些单词也存储在数组中。它看起来有点像这样:

$words = array(
    ["Line0"] => array (
        ["Word0"] => array( 
            ["Name"] => "RandomWord",
            ["DatabasePos"] => 15,
            ["RelationsInDatabase"] => array (
                89, //So this is clearly the same database pos as Word1 on Line0.
                27, //let's assume there's a word on line15 that has this database pos
                )
            ),
        ["Word1"] => array (
            ["Name"] => "SomeOtherRandomWord",
            ["DatabasePos"] => 89,
            ["RelationsInDatabase"] => array (
                NULL
                )
            )
        ),
    ["Line1"] => array (
        ["Word0"] => .... ,
        ..
        ...
        ...
    )
);

等等

我想遍历这个数组,并找到与其他单词相关的单词。然后,将与它们相关的行和单词附加到同一个数组中。例如:

$words = array(
    ["Line0"] => array (
        ["Word0"] => array( 
            ["Name"] => "RandomWord",
            ["DatabasePos"] => 15,
            ["RelationsInDatabase"] => array (
                89, //So this is clearly the same database pos as Word1 on Line0.
                27, //let's assume there's a word on line15 that has this database pos
                ),
            ["RelationsInLinesOfText"] => array ( //I want to loop through and add this element to the array.
                [0] => array("Line0", "Word1"),
                [1] => array("Line15", "Word3")
                )
            ),
        ["Word1"] => array (
            ["Name"] => "SomeOtherRandomWord",
            ["DatabasePos"] => 89,
            ["RelationsInDatabase"] => array (
                NULL
                )
            )
        ),
    ["Line1"] => array (
        ["Word0"] => .... ,
        ..
        ...
        ...
    )
);

我的问题是我最终得到了一个非常混乱的 4/5 级深的“foreach”循环,并且由于混乱的代码而最终犯了一堆难以调试的错误。有没有一种干净的方法可以做到这一点,也许使用 RecursiveArrayIterator 之类的东西?我对 PHP 迭代器对象没有太多经验。

谢谢您的帮助

4

1 回答 1

1

这是一个丑陋的解决方案,但我认为无论如何你都需要遍历整个数组两次嵌套:

function searchLink($iLink, &$rgData)
{
   $rgResult = [];
   foreach($rgData as $sLine=>$rgLines)
   {
      foreach($rgLines as $sWord=>$rgWord)
      {
         if($rgWord['DatabasePos']==$iLink)
         {
            $rgResult[]=['line'=>$sLine, 'word'=>$sWord];
         }
      }
   }
   return $rgResult;
}

//$rgData is a data array
foreach($rgData as $sLine => $rgLines)
{
   foreach($rgLines as $sWord=>$rgWord)
   {
      foreach($rgWord['RelationsInDatabase'] as $iPosition)
      {
         $rgData[$sLine][$sWord]['RelationsInLinesOfText'][]=searchLink($iPosition, $rgData);
      }
   }
}

另外,由于您没有提到位置是否唯一,['line'=>$sLine, 'word'=>$sWord]因此将向每个条目写入一个数组。

于 2013-08-27T10:39:17.787 回答