【问题标题】:Different Array Values depending on the if statement不同的数组值取决于 if 语句
【发布时间】:2012-09-16 05:45:00
【问题描述】:

我正在构建一个网络爬虫,它会从提交的一个网址中找到的链接中扫描链接、标题和元描述

我认为这个 if 语句是正确的。 $description 是保存数组 $link 中所有描述的变量。但我注意到并非所有网站都有元描述(例如维基百科),所以我决定如果描述为空,我希望前 20 个字符作为描述。 (顺便说一句,一切的功能和调用都有效,我只是想让你看到它)

     if ($description == '') {
    $html = file_get_contents($link);    
    preg_match('%(<p[^>]*>.*?</p>)%i', $html, $re);
    $res = get_custom_excerpt($re[1]);
    echo "\n";
    echo $res;
    echo "\n";

    }

但是,在数组中,链接存储在[link]中,链接的标题存储在[title]中,描述存储在[description]中。但我不知道如何处理将 $res 添加到我的数组并仅在 if 语句有效时使用。

$output = Array();

   foreach ($links as $thisLink) {
   $output[] = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink), getMetas($res));
     } 
    print_r($output);

【问题讨论】:

  • 不确定你的变量/数组的构造,但是当你在if块中时,为什么不在检测时将$res的内容插入到数组中呢?链接、标题和元数据存储在哪里……在关联数组中?对象?
  • 你在哪里设置 $links ?显示代码。

标签: php


【解决方案1】:

您可以使用 array_push() 将 $res 添加回您的数组,然后根据需要评估该数组;不是 100% 确定您要做什么...

【讨论】:

    【解决方案2】:

    从你的措辞我认为你想这样做:

    $outputs = array();
    
    foreach ($links as $thisLink) {
        $output = array("link" => $thisLink, "title" => Titles($thisLink), "description" => getMetas($thisLink));
    
        if ($output['description'] == null) {
            $output['description'] = getMetas($res);
        }
    
        $outputs[] = $output;
    }
    

    您可能需要调整 if 语句,因为我不知道 getMetas() 在没有描述时返回什么。

    【讨论】:

    • 哦,我错过了一个角色。现在它在 $outputs 变量中累积链接。请使用 var_dump 检查 $outputs。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多