2013-10-24 43 views
0

的mysql这是JavaScript的序列化数组:序列化数组保存到PHP和排序依据

[{"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 
*********************************** 

谢谢回答。

+2

你知不知道如何反序列化呢?你知道如何编写一个循环吗?你知道如何进行查询吗? – Ryan

+0

该JSON如何对应该表?你怎么知道在每个领域放什么? –

+0

@RocketHazmat:'children'中的东西被放入与其父对应的'subsite_id'中,并且所有东西都被放入'orderby'中,以依赖它在包含它的数组中的位置。 – Ryan

回答

1

这可能不是最好的解决方案,但它肯定是a的解决方案。最近,我了解到RecursiveIterator和他们的表弟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"; 
} 

DEMO:https://eval.in/57189

+0

谢谢!这项工作很完美! –

+0

不客气!很高兴我能帮忙:-D –