简体   繁体   English

PHP 循环遍历关键字数组

[英]PHP loop through array for keywords

I'm trying to loop through an array of arrays with the a foreach loop.我正在尝试使用 foreach 循环遍历数组数组。 Im having trouble targeting just the second element in the individual arrays to check for keywords.我无法仅针对单个数组中的第二个元素来检查关键字。

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

I used this before to get a specific element from an array but I'm not sure why I can't now.我之前使用它从数组中获取特定元素,但我不确定为什么我现在不能。 Here is my error:这是我的错误:

Error:错误:

Undefined offset: 2 line: 62未定义偏移量: 2 行:62

Code:代码:

$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';
   }
}

You are filling the data array with arrays of length 2. This means you can access them with the indices 0 and 1 (arrays are 0 based in php).您正在使用长度为 2 的数组填充data数组。这意味着您可以使用索引 0 和 1 访问它们(数组在 php 中为 0)。 With $pos[2] you try to access it with index 2 which causes the invalid offset exception.使用$pos[2]您尝试使用索引 2 访问它,这会导致无效偏移异常。

In general I would not mix accessing an array by index and key.一般来说,我不会混合通过索引和键访问数组。 Change the code to $pos['value'] .将代码更改为$pos['value'] It's a strange feature of php anyway.无论如何,这是 php 的一个奇怪功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM