【问题标题】:Create array from php form field using foreach then save to json file使用 foreach 从 php 表单字段创建数组,然后保存到 json 文件
【发布时间】:2020-08-24 15:11:43
【问题描述】:

我正在尝试将 PHP 表单的字段值保存到 json 文件中。我已经尝试了该站点上的一些解决方案,这些解决方案有所帮助,但我遇到了一个问题,即它没有获取字段值并且没有返回任何错误(我检查了日志)。我是 PHP 新手,所以我可能犯了一个菜鸟错误。

我正在尝试使用此处发布的解决方案 https://stackoverflow.com/a/17923066/1747477

另外,我需要用 JSON 文件中已经存在的索引“bundled_plugins”替换嵌套数组,而不是将其附加到现有的嵌套数组中。我正在使用 array_push 但我知道我需要使用 array_replace 但我不知道如何定位特定索引。如果有人能指出我正确的方向吗?

表格

<form action="<?php $_SERVER["PHP_SELF"]; ?>" method="post" role="form">

<div class="form-group">

    <label for="plugin1">Plugin 1</label>
    <input type="url" class="form-control" title="Enter the plugin's download URL" name="plugin[1][download]" id="plugin1_download" placeholder="https://downloads.wordpress.org/plugin/plugin-name.latest-stable.zip" value="<?php echo $settings->bundled_plugin_1_download; ?>" pattern="https://.*" size="100" required>

</div>

<div class="form-group">

    <input type="text" class="form-control" title="Enter the plugin's basename" name="plugin[1][file]" id="plugin1_file" placeholder="directory-name/primary.php" value="<?php echo $settings->bundled_plugin_1_file; ?>" size="100" required>

</div>

<div class="form-group">

    <label for="plugin2">Plugin 2</label>
    <input type="url" class="form-control" title="Enter the plugin's download URL" name="plugin[2][download]" id="plugin2_download" placeholder="https://downloads.wordpress.org/plugin/plugin-name.latest-stable.zip" value="<?php echo $settings->bundled_plugin_2_download; ?>" pattern="https://.*" size="100">

</div>

<div class="form-group">

    <input type="text" class="form-control" title="Enter the plugin's basename" name="plugin[2][file]" id="plugin2_file" placeholder="directory-name/primary.php" value="<?php echo $settings->bundled_plugin_2_file; ?>" size="100">

</div>

<div class="form-group">

    <label for="plugin3">Plugin 3</label>
    <input type="url" class="form-control" title="Enter the plugin's download URL" name="plugin[3][download]" id="plugin3_download" placeholder="https://downloads.wordpress.org/plugin/plugin-name.latest-stable.zip" value="<?php echo $settings->bundled_plugin_3_download; ?>" pattern="https://.*" size="100">

</div>

<div class="form-group">

    <input type="text" class="form-control" title="Enter the plugin's basename" name="plugin[3][file]" id="plugin3_file" placeholder="directory-name/primary.php" value="<?php echo $settings->bundled_plugin_3_file; ?>" size="100">

</div>

<div class="form-group">

    <label for="plugin4">Plugin 4</label>
    <input type="url" class="form-control" title="Enter the plugin's download URL" name="plugin[4][download]" id="plugin4_download" placeholder="https://downloads.wordpress.org/plugin/plugin-name.latest-stable.zip" value="<?php echo $settings->bundled_plugin_4_download; ?>" pattern="https://.*" size="100">

</div>

<div class="form-group">

    <input type="text" class="form-control" title="Enter the plugin's basename" name="plugin[4][file]" id="plugin4_file" placeholder="directory-name/primary.php" value="<?php echo $settings->bundled_plugin_4_file; ?>" size="100">

</div>

<div class="form-group">

    <label for="plugin5">Plugin 5</label>
    <input type="url" class="form-control" title="Enter the plugin's download URL" name="plugin[5][download]" id="plugin5_download" placeholder="https://downloads.wordpress.org/plugin/plugin-name.latest-stable.zip" value="<?php echo $settings->bundled_plugin_5_download; ?>" pattern="https://.*" size="100">

</div>

<div class="form-group">

    <input type="text" class="form-control" title="Enter the plugin's basename" name="plugin[5][file]" id="plugin5_file" placeholder="directory-name/primary.php" value="<?php echo $settings->bundled_plugin_5_file; ?>" size="100">

</div>

<div class="form-group">

    <button id="bundle_plugins" type="submit" name="bundle_plugins" class="btn btn-md btn-success">Save</button>

</div>

PHP 函数

public function bundle_plugins() {

    $settings = "settings.json";
    $arr_data = array();

    $plugins = array();
    foreach($_POST['plugin'] as $key => $val) {
        $plugins[] = array(
            'download' => $_POST['plugin'][$key],
            'file' => $_POST['plugin'][$key]
        );
    }

    // Get data from existing json file
    $jsondata = file_get_contents($settings);

    // Converts json data into array
    $arr_data = json_decode($jsondata, true);

    // Push user data to array
    array_push($arr_data, $plugins);

    // Convert updated array to JSON
    $jsondata = json_encode($arr_data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

    //write json data into data.json file
    if(file_put_contents($settings, $jsondata)) {
        echo "<div class='alert alert-success' role='alert'>Plugins successfully bundled!</div>";
    }
    else {
        echo "<div class='alert alert-danger' role='alert'><strong>ERROR</strong> Please check you have entered the plugin download URL and basename correctly and try again.</div>";
    }

}

JSON

{
    "bundled_plugins": [
        {
            "download": "https://downloads.wordpress.org/plugin/classic-editor.latest-stable.zip",
            "file": "classic-editor/classic-editor.php"
        },
        {
            "download": "https://downloads.wordpress.org/plugin/defender-security.latest-stable.zip",
            "file": "defender-security/wp-defender.php"
        }
    ]
}

编辑:

{
    "bundled_plugins": [
        {
            "download": "https://downloads.wordpress.org/plugin/classic-editor.latest-stable.zip",
            "file": "classic-editor/classic-editor.php"
        },
        [
            {
                "download": "https://downloads.wordpress.org/plugin/classic-editor.latest-stable.zip",
                "file": "classic-editor/classic-editor.php"
            },
            {
                "download": "",
                "file": ""
            },
            {
                "download": "",
                "file": ""
            },
            {
                "download": "",
                "file": ""
            },
            {
                "download": "",
                "file": ""
            }
        ]
    ]
}

编辑 2:

如果我切换到array_replace,这是 json 文件。 bundled_plugins 索引已删除。

[
    {
        "download": "https://downloads.wordpress.org/plugin/classic-editor.latest-stable.zip",
        "file": "classic-editor/classic-editor.php"
    },
    {
        "download": "https://downloads.wordpress.org/plugin/test.latest-stable.zip",
        "file": "classic-editor/test.php"
    }
]

解决方案

public function bundle_plugins() {

        $settings = "settings.json";
        $arr_data = array();
        
        $plugins = array();
        foreach($_POST['plugin'] as $key => $val) {
            if( !empty($_POST['plugin'][$key]['download']) && !empty($_POST['plugin'][$key]['file'])) {
                $plugins['bundled_plugins'][] = $_POST['plugin'][$key];
            }
        }

        // Get data from existing json file
        $json = file_get_contents($settings);

        // Converts json data into array
        $arr_data = json_decode($json, true);

        // Push user data to array
        $arr_data = array_replace($arr_data, $plugins);

        // Convert updated array to JSON
        $json = json_encode($arr_data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

        //write json data into data.json file
        if(file_put_contents($settings, $json)) {
            echo "<div class='alert alert-success' role='alert'>Plugins successfully bundled!</div>";
        }
        else {
            echo "<div class='alert alert-danger' role='alert'><strong>ERROR</strong> Please check you have entered the plugin download URL and basename correctly and try again.</div>";
        }

    }

【问题讨论】:

  • 1.真的有input type="url" 类型吗? 2.你需要$_POST['plugin'][$key]['file']$_POST['plugin'][$key]['download']
  • @AbraCadaver 显然是w3schools.com/tags/att_input_type_url.asp。会尝试你的建议。
  • 好的,以前没用过。
  • @AbraCadaver 尝试过,但仍然得到相同的结果。没有变化,也没有错误......这与$_POST['plugin'][$key]['file'] 很可能是问题有关。不抓取输入值。
  • 你有没有打电话给bundle_plugins()?最后你会得到什么回声?

标签: php arrays json foreach


【解决方案1】:

首先,您忽略了 POST plugindownloadfile。其次,只需将新数组合并到现有数组中:

foreach($_POST['plugin'] as $key => $val) {
    $plugins[] = array(
        'download' => $_POST['plugin'][$key]['download'],
        'file' => $_POST['plugin'][$key]['file']
    );
}

// Get data from existing json file
$jsondata = file_get_contents($settings);

// Converts json data into array
$arr_data = json_decode($jsondata, true);

$arr_data = array_merge($arr_data['bundled_plugins'], $plugins);

循环可能更简单,因为密钥已经在 POST 中:

foreach($_POST['plugin'] as $key => $val) {
    $plugins[] = $_POST['plugin'][$key];
}

或者也许只是当您不需要做任何其他事情时: $plugins = $_POST['plugin'];

但是,您可能希望在添加到 $plugins 数组之前检查 POST 值是否为 !empty(),并在合并之前检查 $plugins 数组,以免出现空值。

【讨论】:

  • 您的代码建议运行良好。我切换到array_replace,它可以工作,但会去掉 bundled_plugins 索引。请参阅问题中的我的 EDIT 2。
  • 经过反复试验终于弄明白了。发布最终解决方案。感谢您的所有帮助!
猜你喜欢
  • 2011-01-05
  • 2011-05-09
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多