php - 如何在 PHP 的 foreach 循环中使用 array_push?

标签 php foreach array-push

这是我尝试过的示例

<?php
 include 'spider/classes/simple_html_dom.php';
 $html = new simple_html_dom();
 $html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
 $e = $html->find("h2", 0);
 $key = array();
 if($e->plaintext != ""){
 foreach($html->find("h2", 0) as $e){
    //echo $e->plaintext;
    array_push($key, $e->plaintext);
  }
 } else {
     echo "error";
 }
 print_r($key);
 ?>

结果:
数组 ( [0] => [1] => [2] => [3] => [4] => [5] => 标题 1此标题 2

[6] => [7] => )

如何使用 array_push 创建数组?

最佳答案

当您尝试此代码时会发生什么? 我删除了第一个“find”,还在互联网上找到了一个示例,其中“find”的第二个参数没有设置。

<?php
 include 'spider/classes/simple_html_dom.php';
 $html = new simple_html_dom();
 $html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
 $key = array();
 if(isset($html)){
 foreach($html->find("h2") as $e){
    //echo $e->plaintext;
    array_push($key, $e->plaintext);
  }
 } else {
     echo "error";
 }
 print_r($key);
 ?>

说明:

// Find all anchors, returns a array of element objects
$ret = $html->find('a');

// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);

关于php - 如何在 PHP 的 foreach 循环中使用 array_push?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901712/

相关文章:

javascript - Jquery推送功能

javascript - 使用 jquery 在 php cURL 中搜索

javascript - 将对象插入数组会产生相同的值

PHP 向 foreach 中使用的数组添加新键

java - 增强了(或 'for each' )循环迭代到它刚刚删除的元素 - 抛出错误

c# - 即使MSDN另有建议,为什么Parallel.ForEach比AsParallel()。ForAll()快得多?

javascript - forEach 在 iOS Safari 上不起作用

javascript - 从 HTML5 网络摄像头获取图像的 src

php - 多数据库查找 VS fetch all + array search,哪个更高效

php - 检查pdo中mysql存储函数的 bool 返回值