PHP解析多个已发布变量数组

时间:2012-09-27 12:20:12

标签: php arrays object

关于我在做什么的一些背景知识。我正在使用Excel电子表格,其中包含大量名称和电子邮件,并根据一系列过滤器向他们发送较小的列表子集。为了完成过滤,我将每个Excel行分成一个JSON数组并将其放入DOM中,然后我使用Javascript / jQuery填充一些隐藏的字段。

在完成所有过滤之后,我有大约十几个以逗号分隔的列表,然后我在发布表单时使用PHP explode转回数组。我需要能够使用特定于该人的数据切换电子邮件正文中的一些变量。如果不考虑太多细节并且让您感到困惑,我基本上需要使用PHP发布数组中的值替换电子邮件正文中的某些值。

我将发布的数据拉入并使用以下代码将其转换为数组:

//Bring in Hidden fields - turn into arrays
$companies = explode(",", $_POST['companies']);
$kw_signed = explode(",", $_POST['kw_signed']);
$header_rows = explode(",", $_POST['header_rows']);
$first_names = explode(",",$_POST['first_names']);
$emails = explode(",",$_POST['emails']);
$full_names = explode(",",$_POST['full_names']);
$markets = explode(",",$_POST['market']);
$zones = explode(",",$_POST['zones']);
$cities = explode(",",$_POST['cities']);
$states = explode(",",$_POST['states']);
$zipcodes = explode(",",$_POST['zipcodes']);
$p_factors = explode(",",$_POST['perf_factor']);

在我创建了一堆数组之后,我使用for循环来遍历数组和foreach,用它们各自的值替换电子邮件正文中的变量,如下所示:

for($i=0; $i<$count; $i++) {
    //Create temp variable for body temp    
    $body_temp = $email_text;   
    //Replace header strings with value
    foreach($header_rows as $header) {
        if($header == '{first_name}') {
            $body_temp = str_replace($header, $first_name[$i], $body_temp);
        } else if($header == '{email}') {
            $body_temp = str_replace($header, $emails[$i], $body_temp);
        } else if($header == '{company}') {
            $body_temp = str_replace($header, $companies[$i], $body_temp);
        } else if($header == '{zone}') {
            $body_temp = str_replace($header, $zones[$i], $body_temp);
        } else if($header == '{market}') {
            $body_temp = str_replace($header, $markets[$i], $body_temp);
        } else if($header == '{city}') {
            $body_temp = str_replace($header, $cities[$i], $body_temp);
        } else if($header == '{state}') {
            $body_temp = str_replace($header, $states[$i], $body_temp);
        } else if($header == '{zip}') {
            $body_temp = str_replace($header, $zipcodes[$i], $body_temp);
        } else if($header == '{facility_type}') {
            $body_temp = str_replace($header, $facility_type[$i], $body_temp);
        }
    }

所以,现在问题。
如何更有效地进行更换?
我是否使用包含信息的数组创建一个对象并循环遍历数组以替换每个已发布名称的对象变量,或者我是否完全以错误的方式进行此操作?任何见解将不胜感激

1 个答案:

答案 0 :(得分:0)

您可以按以下方式替换

for($i=0; $i<$count; $i++) {
    //Create temp variable for body temp    
    $body_temp = $email_text;
    $body_temp = str_replace(array('{firsname}','{email}'), array($first_name[$i],$emails[$i]), $body_temp);  
}