我需要将多调整PHP数组的特定元素与同一数组中的某些其他元素进行比较

时间:2013-08-27 10:27:55

标签: php mysql arrays iteration

我有一个数组,其中包含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迭代器对象没有多少经验。

感谢您的帮助

1 个答案:

答案 0 :(得分: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]