0

这是 javascript 序列化数组:

[{"id":1},{"id":2},{"id":3,"children":[{"id":4,"children":[{"id":5},{"id":6},{"id":7}]},{"id":8}]}]

如何使用 php 将此(动态)保存到 mysql,如下所示:

***********************************
|  id  |   subsite_id  | orderby  |
   1           0            0
   2           0            1
   3           0            2
   4           3            0
   5           4            0
   6           4            1
   7           4            2
   8           3            1
***********************************

感谢您的回答。

4

1 回答 1

1

这可能不是最好的解决方案,但它肯定是一个解决方案。最近,我了解到RecursiveIterators 和他们的表弟,RecursiveIteratorIterator。因此,我自己承担了在我编写的所有代码中使用它们的责任(相关的 XKCD:https ://xkcd.com/208/ )。

我很快就破解了这个:

class ChildIDIterator implements RecursiveIterator{
    private $_array;
    private $_position = 0;
    private $_parent;

    public function __construct(array $array, $parent=0) {
        $this->_array = $array;
        $this->_parent = $parent;
    }

    function valid(){
        return isset($this->_array[$this->_position]);
    }

    function current() {
        return $this->_array[$this->_position]['id'];
    }

    function next() {
        $this->_position++;
    }

    function rewind() {
        $this->_position = 0;
    }

    function key() {
        return $this->_position;
    }

    function hasChildren(){
        return isset($this->_array[$this->_position]['children']);
    }

    function getChildren(){
        return new self(
            $this->_array[$this->_position]['children'],
            $this->_array[$this->_position]['id']
        );
    }

    function getParent(){
        return $this->_parent;
    }
}

这会递归地遍历您的(解码的)数组并返回 id 值。要使用它,您可以这样做:

$json = '[{"id":1},{"id":2},{"id":3,"children":[{"id":4,"children":[{"id":5},{"id":6},{"id":7}]},{"id":8}]}]';

$array = json_decode($json, TRUE);

$iterate = new RecursiveIteratorIterator(new ChildIDIterator($array), RecursiveIteratorIterator::SELF_FIRST);

foreach($iterate as $order=>$id){
    echo "UPDATE sites SET subsite_id={$iterate->getParent()}, orderby={$order} WHERE id={$id};\n";
}

演示:https ://eval.in/57189

于 2013-10-24T16:58:33.033 回答