如何使用PHP从JSON获取父级和子级深度级别?

时间:2019-02-09 17:47:32

标签: php mysql sql arrays json

我有一个像这样的树结构Image

并获得这样的JSON值

    [{"id":1,"children":[{"id":3,"children":[{"id":9}]}]}]

我想找到该孩子的孩子深度级别和父ID,并使用PHP更新它。

我的脚本代码是:

    $data = json_decode($_POST['output']);
    foreach($data as $sort_value=>$id) {
    $cats_id = $id->id;

    mysqli_query($db, "UPDATE ads_categories SET category_order = '".$sort_value."', category_parent = NULL, category_root = '".$parent."' WHERE category_id = '".$cats_id."'");

    if(isset($id->children)) {
       foreach($id->children as $sort_next=>$id_next) {
            $cat_id = $id_next->id;
            $parent = $id->id;
            mysqli_query($db, "UPDATE ads_categories SET category_order = '".$sort_next."', category_parent = '".$parent."', category_root = '".$parent."' WHERE category_id = '".$cat_id."'");

        }
    }
}

它仅查找和更新第一个孩子。

找到了类似的东西,但是没有运行?它显示空白页:

$jsonString = '[{"id":1,"children":[{"id":3,"children":[{"id":9,"children":[{"id":8}]}]}]},{"id":10,"children":[{"id":11,"children":[{"id":13}]},{"id":12}]}]';
$jsonArray = json_decode($jsonString);

function read_tree_recursively($items, $parent_id = 0, $result = array(), $level = 0) {
    foreach($items as $child) {
        $result[$child->id] = array(
            'id' => $child->id,
            'parent_id' => $parent_id,
            'level' => $level
        );

        if (!empty($child->children)) {
            $result = read_tree_recursively($child->children, $child->id, $result, $level+1);
        }
    }
    return $result;
}

// usage
read_tree_recursively($jsonArray);

0 个答案:

没有答案