匹配数组后打印下一个数组

时间:2017-08-15 15:32:28

标签: php arrays

我有一个数组数组,其中包含带有值的数组键,例如:

options(java.home = "C:\\Program Files\\Java\\jdk1.8.0_74\\")
library(rJava)
library(XLConnect)
workbook <- loadWorkbook("test.xls")
readWorksheet(workbook, sheet = "Sheet0", keep = c(1,2,5))

我的数组前缀包含:

$text = [
        [
         'Hotel'     => 'N',
         'Jayakarta' => 'NE',
         'Jaya'      => 'NE',
         'sangat'    => 'ADV',
         'nyaman'    => 'ADJ',
         'ditempati' => 'V.'
        ]
        ,
        [
         'Andi'     => 'NOB',
         'menginap' => 'V',
         'di'       => 'PREP',
         'Hotel'    => 'N',
         'Neo'      => 'NE',
         'Malioboro => 'NE',
         'selama'   => 'N',
         'satu'     => 'NUM',
         'minggu'   => 'N.'
        ]
    ];

如果$ prefix元素在$ text数组中,那么我将检查文本的下一个数组值。如果数组值是N或NE,那么我将从前缀文本输出,直到包含值N或NE的数组的末尾。

这就是我现在正在做的事情:

$prefix = [ [0] => Hotel [1] => Hostel [2] => Losmen [3] => Motel [4] => Penginapan [5] => Pesanggrahan [6] => Pondok [7] => Wisma ]

我得到的输出:

foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            echo $tokkey;
            $next = next($tok);
            if($tokvalue == "N" or $tokvalue == "NE"){
                echo key($tok);
            }     
        }
   }
}

预期输出应为:

Hotel Jayakarta, Hotel menginap

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

根据我的理解,您需要替换仅运行一次的if(),以及while()字符串为NE或N时运行的next()

foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            echo $tokkey;
            next($tok);
            while($tokvalue == "N" || $tokvalue == "NE")
            {    echo key($tok); 
                 next($tok); 
                 $tokvalue = current($tok);
            }
            }
        }
        echo "\n";      
   }
}

答案 1 :(得分:0)

以下是我为获得所需的输出而采取的步骤。

1)如果tokkey出现在前缀数组中,则调用一个函数。

2)从与前缀数组匹配的元素开始创建一个新数组。

3)循环新阵列并检查下一个值是否为&#39; N&#39;或者&#39; NE&#39;

4)从数组中显示这些键。

foreach($text as $index => $tok){
    foreach ($tok as $tokkey => $tokvalue) {
        if(in_array($tokkey, $prefix)){
            getKeys($tokkey,$tok);
            echo "<br/>";
        }
    }
}

function getKeys($tokkey,$tok){
    $flag = 0;
    echo $tokkey.' ';
    foreach($tok as $k=>$v){
        if($k==$tokkey){
            $flag = 1;
        }
        if($flag){
            $new_array[$k]=$v;
        }
    }
    foreach($new_array as $k=>$v){
        $ff = next($new_array);
        if(($ff == 'NE' || $ff == 'N')){
             echo key($new_array).' ';
        }
    }
}

Out Put:

Hotel Jayakarta Jaya
酒店Neo Malioboro selama

http://sandbox.onlinephpfunctions.com/code/2777d3ab3d34c941c23886d42e537cde7fff2351