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