在PHP中解析CSV - 在满足条件时抓住所有兄弟姐妹

时间:2013-11-20 21:14:06

标签: php csv multidimensional-array fgetcsv

我正在尝试在满足某个条件时获取数组的值。我似乎发现自己处在一个真正的泡菜中,我希望在这件事上有帮助。我还是PHP新手,巩固了我在数组和循环方面的技能。我正在使用php并尝试解析将每天上传的csv文件。然后我需要解析这个csv文件并将值插入到我们的客户报告系统中。

$rows = array();    
$file = file('prerolldaily.csv');   
$rows = $file;
foreach($rows as $rowsInArray){
    $details = str_getcsv($rowsInArray);
    var_dump($details);
    foreach($details as $key => $value){
        //var_dump($value);
        if ($value === 'CLIENT A') {
            // Grab all sibling values
        }
    }
}

这是$ details的var_dump ......

array (size=12)
  0 => string 'switch active/paused CLIENT A CLIENT A Sites Ads Pre-roll (30s)' (length=69)
  1 => string 'Day 12 out of 19 Nov 8, 2013 Nov 26, 2013' (length=41)
  2 => string '$20.00' (length=6)
  3 => string '$50.00' (length=6)
  4 => string '3,360' (length=5)
  5 => string '12' (length=2)
  6 => string '0.36%' (length=5)
  7 => string '57%' (length=3)
  8 => string '$14.46' (length=6)
  9 => string '$48.58' (length=6)
  10 => string 'edit placement copy placement delete see report attach ad' (length=57)
  11 => string 'CLIENT A' (length=11)

array (size=12)
  0 => string '' (length=0)
  1 => string '' (length=0)
  2 => string '' (length=0)
  3 => string '' (length=0)
  4 => string '' (length=0)
  5 => string '' (length=0)
  6 => string '' (length=0)
  7 => string '' (length=0)
  8 => string '' (length=0)
  9 => string '' (length=0)
  10 => string '' (length=0)
  11 => string '' (length=0)

array (size=12)
  0 => string 'switch active/paused CLIENT B CLIENT B Sites Ads Pre-roll (30s)' (length=91)
  1 => string 'Day 13 out of 20 Nov 7, 2013 Nov 26, 2013' (length=41)
  2 => string '$20.00' (length=6)
  3 => string '$50.00' (length=6)
  4 => string '3,246' (length=5)
  5 => string '8' (length=1)
  6 => string '0.25%' (length=5)
  7 => string '61%' (length=3)
  8 => string '$14.88' (length=6)
  9 => string '$48.30' (length=6)
  10 => string 'edit placement copy placement delete see report attach ad' (length=57)
  11 => string 'CLIENT B' (length=22)

有关如何在满足客户端时定位兄弟姐妹的任何帮助都会非常有用。谢谢!

1 个答案:

答案 0 :(得分:0)

我希望我能正确理解你

$rows = array();    
$file = file('prerolldaily.csv');   
$rows = $file;
$c = 0; 
$selected_array = "";

foreach($rows as $rowsInArray){
    $details = str_getcsv($rowsInArray);

    foreach($details as $key => $value){
        foreach ($value as $k => $v){
            if ($v == "CLIENT A"){
                $selected_array = $c;
            }
        }
        $c++;
    }
}

print_r($details[$selected_array]);

因此,我们正在创建一个计数($c),它将跟踪我们所在的主数组中的哪个级别($details_array),以及一个空变量来存储哪个数组是正确一。我们遍历主数组($details_array),并在该循环中循环遍历子数组值。

如果我们找到匹配值,我们将$selected_array值设置为计数($c),因为这是我们找到值的数组的键

这可以通过在基于值找到正确的数组时断开循环来进一步优化,但这取决于您的用例(是否需要外部循环继续)