【问题标题】:Add a value to a json file with php使用 php 向 json 文件添加一个值
【发布时间】:2022-11-15 07:13:25
【问题描述】:

我有一个用于 Twitch Bot 的 json 文件,我希望能够使用 php 表单添加命令。 我想知道仅使用 PHP 而不使用 js 或其他东西是否可行。

我的 JSON 文件采用这种格式:

{"commands": {"discord": "Discord server : link", "hello": "hello there!"}, "counter": 2}

我想添加这样的值:

{"commands": {"discord": "Discord server : link", "hello": "hello there!", "newcommand": "new command!"}, "counter": 2}

我已经尝试过这样的事情,但这没有用。

我的 HTML 表单:

<form action="#" method="post">
        <label for="nom_commande">Nom de la commande :</label>
        <input type="text" id="nom_commande" name="nom_commande">

        <label for="texte_commande">Texte de la commande :</label>
        <input type="text" id="texte_commande" name="texte_commande">

        <button type="submit">Enregister la commande</button>

    </form>

        $nom_commande = $_POST['nom_commande'];
        $texte_commande = $_POST['texte_commande'];
    
        $data = $nom_commande.":".$texte_commande;
    
        $json = file_get_contents('commands.json');
        $tempArray = json_decode($json,true);
        $tempArray[] = [$nom_commande." => ".$texte_commande];

        $json = json_encode($tempArray);
        
    
        file_put_contents('commands.json', $json);  

我对 JSON 和 PHP 不是很熟悉,很高兴在这里学习新东西!

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    您不会通过分配给 $array[] 来添加到关联数组。您分配给新密钥。

    您还忘记了数组嵌套在 commands 键中。

    $tempArray['commands'][$nom_commande] = $texte_commande;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 2021-03-30
      相关资源
      最近更新 更多