在foreach循环中将值设置为null?

时间:2018-08-07 21:54:06

标签: php

我正在使用CSV文件,并且我希望每个foreach循环末尾的$ row看起来像这样:

bigtable

CSV文件如下所示:

[0] => 3712
[1] => FirstName
[2] => LastName
[4] => sample@string1.co
[5] => sample@string2.co
[6] => sample@string3.co
[7] => sample@string4.co

[0] => 3064
[1] => FirstName
[2] => LastName
[4] => sample@string1.co
[5] => null
[6] => null
[7] => null

[0] => 7651
[1] => FirstName
[2] => LastName
[4] => sample@string1.co
[5] => sample@string2.co
[6] => null
[7] => null


$emails = array(
array('PersonId' => 3712, 'EmailAddress' => 'sample@string1.co'), 
array('PersonId' => 3712, 'EmailAddress' => 'sample@string2.co'), 
array('PersonId' => 3712, 'EmailAddress' => 'sample@string3.co'), 
array('PersonId' => 3712, 'EmailAddress' => 'sample@string4.co'), 
array('PersonId' => 3064, 'EmailAddress' => 'sample@string1.co'),  
array('PersonId' => 7651, 'EmailAddress' => 'sample@string1.co'), 
array('PersonId' => 7651, 'EmailAddress' => 'sample@string2.co'),
array('PersonId' => 5431, 'EmailAddress' => 'sample@string1.co'), 
array('PersonId' => 5431, 'EmailAddress' => 'sample@string2.co'), 
array('PersonId' => 5431, 'EmailAddress' => 'sample@string3.co'));

这就是我现在所拥有的,但是我觉得我还差得远。我似乎无法弄清楚如何基于最大数量的电子邮件将后面的值设置为null。这甚至可行吗?目前,它正在按预期方式添加所有电子邮件,但没有将8个元素总计添加到每个数组中。

2221 FirstName LastName
5431 FirstName LastName
9923 FirstName LastName
7651 FirstName LastName
3712 FirstName LastName
3064 FirstName LastName
8341 FirstName LastName

1 个答案:

答案 0 :(得分:2)

您非常亲密!只需用空值填充$ row数组即可获得8个元素!

while($row = fgetcsv($fp, ",")){
    $count = 3;
    foreach($emails as $email){  
        if($row[0] == $email['PersonId']){
            $row[$count] = $email['EmailAddress'];   
            $count++;
        } else{
            if(!isset($row[$count])){
                $row[$count] = ' ';
            }
        } 
    }
    $row = array_pad($row, 8, null);
    print_r($row);
} 

更新$ row数组的可变最大长度:

$rows = array();
$max = 0;

while($row = fgetcsv($fp, ",")){
    foreach ($emails as $email) {
        if ($row[0] == $email['PersonId']) {
            $row[] = $email['EmailAddress'];
        }
    }
    if (count($row) > $max) {
        $max = count($row);
    }
    $rows[] = $row;
}

foreach ($rows as $row) {
    $row = array_pad($row, $max, null);
    print_r($row);
}

while循环遍历CSV文件并找到PersonId的所有电子邮件地址,并将它们添加到当前的$ row数组中。

一旦找到所有这些,它将计算$ row数组中的元素数。如果此数字大于当前存储在$ max变量中的数字,则$ max变量将使用新数字进行更新。

while循环结束时,$ max包含$ row数组可以具有的最大元素数。

然后,我们需要再遍历数组一次,以空值填充每个数组,以使它们具有相同(最大)数量的元素。