使用PHP更新2个不同的.json文件中的值

问题描述 投票:1回答:1

我有2个.json文件,一个包含类别的问题和答案,一个包含类别。以下是.json文件的一小部分:

category.json

[{
    "category": "Algemeen"
}]

questions.json

[{
    "category": "Algemeen",
    "question": "123",
    "answer": "123",
    "date": "03-12-18 08:48:16"
}]

我已经创建了类别的概述,我可以在其中添加,编辑和删除类别。我还创建了问题和答案的概述。

在类别概述中编辑类别时,它将使用以下代码将其发布到.json文件中:

<?php
    //get the index from URL
    $index = $_GET['index'];

    //get json data
    $data = file_get_contents('category.json');
    $data_array = json_decode($data);

    //assign the data to selected index
    $row = $data_array[$index];
?>

<?php
    if(isset($_POST['save'])){
        //set the updated values
        $input = array(
            'category' => $_POST['category'],
        );

        //update the selected index
        $data_array[$index] = $input;

        //encode back to json
        $data = json_encode($data_array, JSON_PRETTY_PRINT);
        file_put_contents('category.json', $data);

        header('location: category.php');
    }
?>

当使用带有保存按钮的简单表单将“Algemeen”编辑成“Algemeen1”时,这将使用上面的代码编辑category.json。这将变为:

[{
    "category": "Algemeen1"
}]

但是,目标是使类别“同步”,以便在编辑questions.json中也存在的任何类别时,它还会编辑questions.json中的类别值。这必须导致:

[{
    "category": "Algemeen1",
    "question": "123",
    "answer": "123",
    "date": "03-12-18 08:48:16"
}]

我怎样才能做到这一点?

php json
1个回答
0
投票

我会做这样的事情:

<?php
    //get the index from URL
    $index = $_GET['index'];

    //get json data
    $category_data = file_get_contents('category.json');
    $category_data_array = json_decode($data);
    $questions_data = file_get_contents('questions.json');
    $questions_data_array = json_decode($data);

    // get the old category name
    $row = $category_data_array[$index];
    $old_category = $row->category;
?>

<?php
    if(isset($_POST['save'])){
        //set the updated values
        $input = array(
            'category' => $_POST['category'],
        );

        //update the selected index
        $category_data_array[$index] = $input;

        // find old category, make new
        foreach($questions_data_array as $question){
            if ($question->category == $old_category) {
                $question->category = $_POST['category'];
                break;
            }
        }


        //encode back to json
        $category_data = json_encode($category_data_array, JSON_PRETTY_PRINT);
        file_put_contents('category.json', $category_data);
        $questions_data = json_encode($questions_data_array, JSON_PRETTY_PRINT);
        file_put_contents('questions.json', $questions_data);

        header('location: category.php');
    }
?>

警告:我没有测试这段代码。它就像实际代码形状的伪代码。

© www.soinside.com 2019 - 2024. All rights reserved.