如何重新排序PHP中的嵌套元素?

I have a list of nested items (categories) I would like to reorganize, by ordering and nesting depth. I will try to explain:

enter image description here

When I submit a form with jQuery by clicking on blue button SAVE, it process a function inside models/categories_model.php:

public function organize($items){
    if( count($items)){
        foreach($items as $order => $item){
            if($item['item_id'] != ''){
                echo '<pre>'.$order.'</pre>';
                $data = array(
                    'pid'       => (int) $item['parent_id'],
                    'ordering'  => $order
                );
                $this->db
                    ->set($data)
                    ->where($this->_primary_key, $item['item_id'])
                    ->update($this->_table_name);
            }
        }
    }
}

It saves that list like this:

1
    2
    3
4
    5
    6
7
8
    9
    10

Instead of saving it like this:

1
    1
    2
    3
    4
2
    1
    2
3
    1
    2
        1
        2
        3
    3

Instead of getting $order value one by one, it should take into the account it's nested items and start counting the $order from 1, and not continuing a counting from it's parent item.

So when I save it, I want them to be ordered like this, but don't know how to do it:

enter image description here

Someone know how to make it work with nested items pls?

If method recieves items in correct order, this should work:

public function organize($items)
{
    if (!empty($items)) {
        $orderByPid = array();
        foreach ($items as $item) {
            if($item['item_id'] != '') {
                if (!isset($orderByPid[$item['parent_id']])) {
                    $orderByPid[$item['parent_id']] = 0;
                }
                $data = array(
                    'pid'       => (int) $item['parent_id'],
                    'ordering'  => ++$orderByPid[$item['parent_id']]
                );
                $this->db
                    ->set($data)
                    ->where($this->_primary_key, $item['item_id'])
                    ->update($this->_table_name);
            }
        }
    }
}