2015-02-03 7 views
2

개체로 처리해야하는 CSV 파일이 있습니다.CSV에서 중첩 된 개체 만들기

CSV 파일을 열어서 원하는 모든 내용을 얻을 수 있습니다. 문제가 없습니다. CSV 파일의 내용을 머리글로 개체에 일치시켜야합니다. 예를 들면 다음과 같습니다.

Name | Address.Street | Address.Country | Notes.Example.Value 

Object->Name 
Object->Address 
Object->Notes 
etc. 

머리 글자가 미리 무엇인지 알지 못하는데 어떻게 동적으로 처리합니까?

기본적으로 "Prop.Prop.Prop.etc"와 같은 문자열을 중첩 된 개체로 변환하려고합니다.

$headers = array(); // First row of CSV. 
$row = array(); // Current row of CSV. 
$record = new StdClass(); 
foreach ($row as $key => $value) { 
    $properties = explode('.', $headers[$key]); 
    if (count($properties > 1)) { 
    // ??? 
    } 
    else { 
    $record->{$properties[0]} = $value; 
    } 
} 

답변

2

이것은 재귀를 통해 이루어져야합니다. 파싱하려는 속성에 단 한 수준의 깊이가있는 경우 객체 키를 값으로 설정합니다. (이미하고있는)

두 개 이상의 레벨이있는 ​​경우 속성 배열의 첫 번째 요소를 이동하고 나머지 레벨에서 재귀합니다.

귀하의 예제에서 부연 :

<?php 

$headers=[ 
     'Name', 
     'Email', 
     'Address.Street', 
     'Address.Country', 
     'Notes.Example.Value' 
    ]; 

$row=[ 
     'john', 
     '[email protected]', 
     'beale street', 
     'US', 
     '180' 
    ]; 


function setObject(&$object, $properties, $value) { 

    $name=array_shift($properties); 

    if(count($properties)===0) { 
     return $object->{$name} = $value; 
    } else { 
     // if this property isn't set, we declare it as a new object 
     if(!isset($object->{$name}) || !is_object($object->{$name})) $object->{$name} = new StdClass(); 
     return setObject($object->{$name}, $properties,$value); 
    } 
} 


$record = new StdClass(); 

foreach($row as $key=>$value) { 
    $properties = explode('.', $headers[$key]); 
    setObject($record, $properties, $value); 
} 

echo '<pre>'; 
print_r($record); 
echo '</pre>'; 

이 아마 가장 좋은 솔루션은 아닙니다. 약간의 작업을 통해 객체를 앞뒤로 참조로 전달하지 않아도됩니다.