![](/img/trans.png)
[英]PHP- How to split a long array (sentence) into smaller array (keywords) to pass through a foreach loop
[英]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.