简体   繁体   中英

PHP loop through array for keywords

I'm trying to loop through an array of arrays with the a foreach loop. 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

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). With $pos[2] you try to access it with index 2 which causes the invalid offset exception.

In general I would not mix accessing an array by index and key. Change the code to $pos['value'] . It's a strange feature of php anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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