【问题标题】:PHP function only getting last value of arrayPHP函数只获取数组的最后一个值
【发布时间】:2017-07-17 22:29:42
【问题描述】:

好的,所以根据 RamRaider,我已经包含了整个功能。我总是担心当我使变量更通用时会导致变量不匹配或包含拼写错误,所以希望不会出现这些错误。

function my_custom_popular_posts_html_list( $mostpopular, $instance ){
    $output = 'https://startofwebaddress';
            $weekday = date("N")-1;
            $excerpt = ''; 
                $popularPost = get_post($mostpopular[$weekday]->id);
                $popularPostUrl = get_permalink( $popularPost->ID );
                $featuredImgUrl = get_the_post_thumbnail_url($popularPost->ID, 'full');
                $popularPostTitle = esc_html( get_the_title($popularPost) );
                $popularProduct = wc_get_product( $popularPost );
                $popularProductLowPrice = $popularProduct->get_price();
                $excerpt = get_keywords_by_id( $mostpopular[$weekday]->id ); //most popular = 0, 2nd most = 1, 3rd most = 2, etc.
                $initial = array("oldterms");
                $replace   = array("newterms");
                $excerpt = preg_replace($initial,$replace,$excerpt);
                $commonName = str_replace("+"," ",$excerpt);
            $output .= $excerpt;
            $output .= 'endofwebaddress';
        //Get Key for second input
        $First_url = $output;
        $xml = new DOMDocument();
        $ch = curl_init ($First_url); 
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//return xml
        curl_setopt($ch, CURLOPT_HEADER, FALSE);//ignore 
        $xml->loadXML(curl_exec($ch));
        curl_close ($ch);
        $TagName1 = $xml->getElementsByTagName('TagName1')->item(0)->nodeValue;

        //Email URL
        $EmailURL = "urlthatneeds&TagName1=";
        $EmailURL .= $TagName1;
        $EmailURL .= "restofurl";

    $text=file_get_contents($EmailURL);
    $res = preg_match_all(
    "/[a-z0-9]+[_a-z0-9.-]*[a-z0-9]+@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})/i",
    $text,
    $matches
    );
      session_start();
    foreach(array_unique($matches[0]) as $email) {
    $url = 'https://api.sendgrid.com/';
    $user = 'user';
    $pass = 'password';

    $json_string = array(
      'to' => $email,
      'category' => 'most_popular',
      'asm_group_id' => '1141',
    );
    }
    $params = array(
        'api_user'  => $user,
        'api_key'   => $pass,
        'x-smtpapi' => json_encode($json_string),
        'to'        => 'example3@sendgrid.com', //This should be ignored
        'subject'   => $commonName . ' Detailed Protocols and Products.',
        'html'      => 'A whole ton of HTML',
        'text'      => 'Text Version of HTML',
        'from'      => 'me@mail.com',
      );


    $request =  $url.'api/mail.send.json';

    // Generate curl request
    $session = curl_init($request);
    // Tell curl to use HTTP POST
    curl_setopt ($session, CURLOPT_POST, true);
    // Tell curl that this is the body of the POST
    curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
    // Tell curl not to return headers, but do return the response
    curl_setopt($session, CURLOPT_HEADER, false);
    // Tell PHP not to use SSLv3 (instead opting for TLS)
    curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    // obtain response
    $response = curl_exec($session);
    curl_close($session);



    // print everything out
    print_r($response);


    }
    add_filter( 'wpp_custom_html', 'my_custom_popular_posts_html_list', 10, 2 );

    function get_keywords_by_id( $post_id ){

        // Get post data
        $the_post = get_post( $post_id );
        // Get post_content
        $the_post_id = $the_post -> post_title;

        return $the_post_id;
    }

希望我可以简化问题。 $EmailUrl 包含一个包含所有电子邮件地址的字符串。我使用代码中的正则表达式对其进行解析,以获取所有电子邮件地址,并将它们输出到一个数组中。

根据 RichGoldMD(感谢您的建议),我将 session_start() 移到了循环之外,并消除了额外的变量以直接传递电子邮件。这样做时,该函数只会向 example3@sendgrid.com 发送一封电子邮件。同样,如果我采用第一个“to”属性并将其从变量更改为逗号分隔列表,我会收到发送到逗号分隔列表的电子邮件。但是,当我尝试输入数组变量时,或者如果我尝试将数组变量按摩到一个逗号分隔的列表中(这就是我之前所拥有的那种),那么我只会收到一封发送至 example3@sendgrid.com 的电子邮件。如果我将第一个 'to' 属性更改为 [$email, 'myemail@mail.com'],我会收到一封电子邮件发送到 myemail@mail.com 和一封电子邮件发送到数组中的最后一个电子邮件,但没有电子邮件发送发送到其他约 1500 个电子邮件地址。

希望这更有意义,并为缺乏上下文感到抱歉。让我知道更多信息是否有用。如果它对其他人更有用的话,我也很乐意让它更通用一点。

谢谢!

【问题讨论】:

  • 有一点需要注意——在session_start 之前使用echo 是禁止的,并且与在循环中使用session_start() 相结合............不是很好。如果您将代码全部发布而不是位n部分,那么所有查看问题可能会更清楚
  • 我删除了回声,这样应该可以解决这个问题。我还发布了完整的代码。有什么建议吗?

标签: php arrays email variables sendgrid


【解决方案1】:

好的 - 我发现了问题。您的 foreach 循环遍历您的电子邮件数组,每次都替换 $json_string 值,只有最后一次迭代的值被传递到 $params 数组中。

我建议删除 foreach 行和结束大括号,并替换 $json_string :

$json_string = array(
      'to' => array_unique($matches[0]),
      'category' => 'most_popular',
      'asm_group_id' => '1141',
    );

即:

$res = preg_match_all(
    "/[a-z0-9]+[_a-z0-9.-]*[a-z0-9]+@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})/i",
    $text,
    $matches
    );
      session_start();
    // foreach(array_unique($matches[0]) as $email) { <-- Removed foreach
    $url = 'https://api.sendgrid.com/';
    $user = 'user';
    $pass = 'password';

    $json_string = array(
      'to' => array_unique($matches[0]),  // <-- Corrected "to"
      'category' => 'most_popular',
      'asm_group_id' => '1141',
    );
    // } <-- Removed brace
    $params = array(....

--------- 上一个答案如下 -----

绝对将 session_start 移出循环(这不是问题,但无论如何它都不属于循环)。

如果 api 需要一个数组,请使用 implode 删除该行,并直接传递 $email 而不是将其按摩到 $emailAddresses。

implode 语句产生一个字符串,但您的 cmets 表明需要一个数组。

foreach(array_unique($matches[0]) as $email) {         
  $url = 'https://api.sendgrid.com/';
  $user = 'User'; 
  $pass = 'Password'; 
  $json_string = array(
    'to' => $email, 
    'category' => 'my_category',
    'asm_group_id' => '1234', 
  );

...

【讨论】:

  • @TomM0419 $matches[0] 的值是多少?这是你所期望的吗?您可以使用 error_log(print_r($matches[0], true)) 回显它或将其转储到错误日志中;
  • 我还想知道发送网格是否对单个命令中的目标数量有限制 - 你检查过发送网格日志吗?
  • 太棒了。这让我直截了当,真的很接近。如果是 unique_array($matches[0]),则该函数返回一个空数组并默认为 example3@sendgrid.com。如果我将“to”编辑为等于'to' = 'matches[0],,然后将$params 中的“x-smtpapi”更改为'x-smtpapi' =&gt; json_encode(array_unique($json_string)),,那么它可以工作!谢谢您的帮助。旁注:我发现了您与 cancerexpertnow.com 的链接。我也有类似的兴趣,但如果你有时间的话,我想谈谈不同的倾向(博士视角与 MD 视角相称)。可以发一下联系方式吗?
  • 很高兴我能以某种方式提供帮助。
  • 不确定如何安全地发送联系信息 - 但我这里的句柄也是我的推特句柄...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多