php - 数组 foreach 循环 PHP
问题描述
大家好,这里是我的情况:
我正在浏览旧页面,其中包含超过 10 000 条我正在尝试导入 WordPress 的评论。
我正在使用 simple_html_dom.php 库,在这种情况下并不重要。
我正在做的是获取一个包含 24 个第一个帖子的 URL,这些帖子通过它们爬行并获取一个带有评论的元素。
$url = 'http://xx/aktualnosci,wszystkie,0,'.$x.'.html'; //some URL with first 24 posts
$html = file_get_html($url);
$articlesCount = 0;
$commentsCount = 0;
foreach ($html->find('ul.news_codrugi li') as $article) { //get all 24 posts urls
$rawLink = $article->find('a');
foreach ($rawLink as $testLink) {
$link = 'http://xx/'.$testLink->href;
$rawTitle = $testLink->href;
$rawTitle = explode(",", $rawTitle);
$ggTitle = $rawTitle[1];
$htmlNew = file_get_html($link);
foreach ($htmlNew->find('div.komentarz_lista') as $comment) { //comment element
$comm = $comment->find('p');
foreach ($comm as $commText) {
$cleanerCommText = trim(strip_tags($commText));
$item['commRaw'] = $cleanerCommText;
$comments[] = $item;
}
$commentsCount++;
}
$articlesCount++;
}
//unset($articles);
}
此刻一切都很好,我在 Array.xml 中得到了所有评论。问题是评论文本,日期和作者在
没有任何类或 ID 的项目,所以我没有触发器来单独获取它们,所以我的数组是
[0] => 文本,[1] => 日期和作者,[3] => 文本,[4] => 日期和作者等
我正在尝试将其放入一个新数组中,例如 [text] => text, [sign] => date and author :
$x = $commentsCount;
echo $x.'<br />';
$rawComm = array_column($comments, 'commRaw');
$rawCommCount = count($rawComm);
echo 'Pobrane wpisy: '.$rawCommCount.'<br />';
$z = 0;
foreach($rawComm as $commItem) {
if($z % 2 == 0) {
$commArr['text'] = $commItem;
}else{
$commArr['sign'] = $commItem;
//echo $commItem;
}
echo 'Numer wpisu: '.$z.'<br />';
$z++;
}
在最后一个循环中foreach($rawComm as $commItem)
,当我回显这些值时,一切都很好,我已经正确打印了评论文本和评论日期和作者。但是当我试图将它放入一个新数组时$commArr
,我得到了双重项目,所以我的数组是两倍大,所有东西都翻了一番。
为什么我需要在一个新数组中使用它?因为我想把它放到数据库中。
所以在这一点上,我不知道是什么导致了这个问题。有什么帮助吗?:)
谢谢你
解决方案
You are getting the array two times because you are adding whole array value $commItem
to $commArr
during both odd and even numbers using if condition. That's why you are getting array double time.
Replace your code
foreach($rawComm as $commItem) {
if($z % 2 == 0) {
$commArr['text'] = $commItem;
}else{
$commArr['sign'] = $commItem;
//echo $commItem;
}
echo 'Numer wpisu: '.$z.'<br />';
$z++;
}
to this one
foreach($rawComm as $commItem) {
$commArr[] = array('text'=>$commItem[0], 'sign'=>$commItem[1]);
}
I think this might work for you :).
推荐阅读
- javascript - 如果 FullCalendar 4 在从 datesRender 事件加载数据时仅显示当前月份错误的事件?
- uwp - 如何自动增加在 Azure Pipeline 中创建的 .msixupload 文件的包版本号?
- javascript - 除了使用 Axios 和 NodeJS 的文件之外,FormData 不会附加其他变量
- javascript - Javascript 无法在刷新时立即从 getElementById 读取值
- python - 使用 windowsapi reloader 重启
- powerbi - 星型模式的断开连接表中过滤器的奇怪行为
- python-3.x - Python:尝试删除生成以发送电子邮件附件的文件时出错
- ios - Xcode 12.2 中禁用了运行按钮
- python - ABAQUS中的节点位移使用python脚本
- azure-data-factory - azure 数据工厂复制活动仅选择前 100 个文件