2

I have a CSV file which needs to be processed into objects.

I can open the CSV file and get all the contents that I want, no problem there. I need to match the contents of the CSV file by headers into objects. For example:

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

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

How would I handle this dynamically, not knowing what the headers are going to be beforehand?

Essentially I want to turn a string, like "Prop.Prop.Prop.etc" into a nested object.

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

1 Answer 1

2

This should be done through a recursion. If the property you're parsing has only one level of depth, then you set the object key as a value. (which you're already doing)

If it has two or more levels, you shift the first element of the property array and recurse on the remaining levels.

Elaborating in your example:

<?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>';

This is probably not the most elegant solution. With a bit of work you could avoid passing the object by reference back and forth.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.