doulu1020 2017-07-17 22:29
浏览 57
已采纳

PHP函数只获取数组的最后一个值

Ok, so per RamRaider, i've included the entire function. I'm always worried I'll end up mismatching a variable or including a typo when I make it more generic, so hopefully none of those errors.

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;
    }

Hopefully I can simplify the problem. $EmailUrl contains a string with all of the email addresses. I parse it with the regex in the code to get all the email addresses out, and those are output in an array.

Per RichGoldMD (thanks for the suggestions), I moved session_start() outside of the loop, and eliminated extra variables to pass email directly. When doing so, the function just sends an email to example3@sendgrid.com. Again, if I take the first 'to' attribute and change it from the variable, to a comma separated list, I get emails sent to the comma separated list. However, when I try to input the array variable, or if I try to massage the array variable into a comma separated list (which was kind of what I previously had up), then I get just an email to example3@sendgrid.com. If I change the first 'to' attribute to [$email, 'myemail@mail.com'], I get an email sent to myemail@mail.com and an email sent to the last email in the array, but no email sends to the other ~1500 email addresses.

Hopefully this makes a little more sense and sorry for the lack of context. Let me know if more info would make this useful. I'm also happy to make this a little more generic if it would make it more useful for other people.

Thanks!

  • 写回答

1条回答 默认 最新

  • doujia1679 2017-07-17 22:44
    关注

    OK - I'v identified the problem. Your foreach loop loops over your email array, replacing the $json_string value each time, only the last iteration's value is passed into the $params array.

    I suggest eliminate the foreach line and end brace, and replace the $json_string thus:

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

    i.e.:

    $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(....
    

    --------- Previous answer follows -----

    Definitely move session_start out of the loop (it's not the problem but it doesn't belong in the loop in any case).

    If the api expects an array, drop the line with implode, and pass $email directly instead of massaging it into $emailAddresses.

    The implode statement results in a string, but your comments indicate that an array is expected.

    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', 
      );
    

    ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services