How can I append a structure entry and set its order? I'd like to attach children to a specific Structure entry in a specific order...


  
  Entry A
  Entry B
  
  Imported Entry 2
  Imported Entry 1
  Imported Entry 3
  
  Entry C
  


I've got a $records array to turn into imported entries:

array(
    'name'      =&gt; 'Whatever',
    'updated_at' =&gt; '2014-02-27T04:14:29Z',
    'position'   =&gt; 1, // int representing the sort order
    [...]
)


As I'm looping through my array to create new Craft Structure Entries, I need to be able to define the parent (Entry B), I'm just not sure how. I've figured out how to attach new children to Entry B, I just don't know how to programmatically set their order. My imagination writes code that looks like this:

$parentCriteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);

$parentCriteria-&gt;search  = 'slug:entry-b';
$parentCriteria-&gt;section = 'sectionName';
$parentCriteria-&gt;type    = 'sectionType';

$entries = $parentCriteria-&gt;find();
$parent = $entries[0];

foreach ($records as $row)
{
    $entry = new EntryModel();

    $entry-&gt;sectionId = 4;
    $entry-&gt;typeId    = 4;
    $entry-&gt;parentId  = $parent-&gt;id;
    $entry-&gt;authorId  = 1;
    $entry-&gt;postDate  = $row-&gt;updated_at;
    $entry-&gt;title     = $row-&gt;name;
    $entry-&gt;sortOrder = $row-&gt;position; // ← quite impossible!

    $success = craft()-&gt;entries-&gt;saveEntry($entry);
}


It's $entry-&gt;sortOrder that's completely made up—how do you attach an entry to a specific parent in a specific order?
If you're adding them all as new entries anyway, why not just sort the records before you create the entries?

usort($records, array($this, 'sortCategoriesByPosition'));


Add that before your foreach loop, then...

private function sortCategoriesByPosition($a, $b)
{
    if ($a-&gt;position == $b-&gt;position)
        return 0; 

    return ($a-&gt;position &lt; $b-&gt;position) ? -1 : 1;
}


Stop trying to make things harder than they should be.