簡體   English   中英

PHP 循環遍歷關鍵字數組

[英]PHP loop through array for keywords

我正在嘗試使用 foreach 循環遍歷數組數組。 我無法僅針對單個數組中的第二個元素來檢查關鍵字。

foreach($data as $pos){
   if (strpos($pos[2],'are') !== false) { //Line 62//
       echo 'true';
   } else{
        echo 'idk what to do';
   }
}

我之前使用它從數組中獲取特定元素,但我不確定為什么我現在不能。 這是我的錯誤:

錯誤:

未定義偏移量: 2 行:62

代碼:

$url = "http://www.ted.com/";
/* store results here */
$data=array();

/* The tags you are interested in finding within the html src */
$tags=array('p','h1');
$keyword=array('technology','ideas');

/* Create the dom object with html from url */
$dom=new htmldom( file_get_contents( $url ), true );
$html=$dom->gethtml();

/* Get all tags */
$col=$html->getElementsByTagName('*');

if( $col->length > 0 ){
    foreach( $col as $tag ) {
        /* Is this a tag we are interested in? */
        if( in_array( $tag->tagName, $tags ) ){
                $data[]=array( 'tag' => $tag->tagName, 'value' => $tag->textContent );
        }
    }
}
$dom=$html=null;
/* Do stuff with the results */


foreach($data as $pos){
   if (strpos($pos[2],'are') !== false) {
       echo 'true';
   } else{
        echo 'idk what to do';
   }
}

您正在使用長度為 2 的數組填充data數組。這意味着您可以使用索引 0 和 1 訪問它們(數組在 php 中為 0)。 使用$pos[2]您嘗試使用索引 2 訪問它,這會導致無效偏移異常。

一般來說,我不會混合通過索引和鍵訪問數組。 將代碼更改為$pos['value'] 無論如何,這是 php 的一個奇怪功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM