将键值对有条件地添加到数组会将带有空值的键添加到数组中。

huangapple go评论69阅读模式
英文:

Adding key-value pair to array conditionally adds the key with a null value to the array

问题

I've translated the code and provided a readable version of the output. If you have any specific questions or need assistance with a particular part of the code, please let me know.

英文:

I am working on an api that requires a json script, but I am making it so I can use the api on my website.

The issue I am stuck on and struggling to find an answer for is when the array is 'compiled'.

If one of my form inputs are null, I want that key-value pair to be non-existent rather than just making the value null.

My current script:

if (isset($_POST['title']) || isset($_POST['description']) || isset($_POST['image-url'])) {
    $embed = TRUE;
} else {
    $embed = FALSE;
}

$data_arr = array("username" => $_POST['username']);

if (isset($_POST['usericon'])) {
    $data_arr["avatar_url"] = $_POST['usericon'];
}

if (isset($_POST['tts']) && $_POST['tts'] == "true") {
    $data_arr["tts"] = $_POST['tts'];
} else {
    $data_arr["tts"] = "false";
}

if (isset($_POST['content'])) {
    $data_arr["content"] = $_POST['content'];
}

if (isset($_POST['file'])) {
    $data_arr["file"] = $_POST['file'];
}

$data_arr["type"] = "rich";

if ($embed) {
    $data_arr["embeds"] = array();

    $embed = array();

    if (isset($_POST['author-name'])) {
        $author = array("name" => $_POST['author-name']);

        if (isset($_POST['author-url'])) {
            $author["url"] = $_POST['author-url'];
        }

        if (isset($_POST['author-icon'])) {
            $author["icon_url"] = $_POST['author-icon'];
        }

        $embed["author"] = $author;
    }

    if (isset($_POST['title'])) {
        $embed["title"] = $_POST['title'];
    }

    if (isset($_POST['title-url'])) {
        $embed["url"] = $_POST['title-url'];
    }

    if (isset($_POST['description'])) {
        $embed["description"] = $_POST['description'];
    }

    if (isset($_POST['color']) && $_POST['color'] != "#000000") {
        $embed["color"] = ltrim($_POST['color'], '#');
    }

    if (isset($_POST['thumbnail-url'])) {
        $embed["thumbnail"] = array("url" => $_POST['thumbnail-url']);
    }

    if (isset($_POST['image-url'])) {
        $embed["image"] = array("url" => $_POST['image-url']);
    }

    if (isset($_POST['footer-txt'])) {
        $footer = array("text" => $_POST['footer-txt']);

        if (isset($_POST['footer-icon-url'])) {
            $footer["icon_url"] = $_POST['footer-icon-url'];
        }

        $embed["footer"] = $footer;
    }

    if (isset($_POST['timestamp']) && $_POST['timestamp'] == 1) {
        $embed["timestamp"] = date("c", strtotime("now"));
    }

    $data_arr["embeds"][] = $embed;
}

var_dump($data_arr);

Output:

array(7) { ["username"]=> string(12) "DS_Announcer" ["avatar_url"]=> string(0) "" ["tts"]=> string(5) "false" ["content"]=> string(4) "test" ["file"]=> string(0) "" ["type"]=> string(4) "rich" ["embeds"]=> array(1) { [0]=> array(7) { ["author"]=> array(3) { ["name"]=> string(0) "" ["url"]=> string(0) "" ["icon_url"]=> string(0) "" } ["title"]=> string(0) "" ["url"]=> string(0) "" ["description"]=> string(0) "" ["thumbnail"]=> array(1) { ["url"]=> string(0) "" } ["image"]=> array(1) { ["url"]=> string(0) "" } ["footer"]=> array(2) { ["text"]=> string(0) "" ["icon_url"]=> string(0) "" } } } }

Readable version:

array(7) { 
    ["username"]=> string(12) "DS_Announcer" 
    ["avatar_url"]=> string(0) "" 
    ["tts"]=> string(5) "false" 
    ["content"]=> string(4) "test" 
    ["file"]=> string(0) "" 
    ["type"]=> string(4) "rich" 
    ["embeds"]=> array(1) { 
        [0]=> array(7) { 
            ["author"]=> array(3) { 
                ["name"]=> string(0) "" 
                ["url"]=> string(0) "" 
                ["icon_url"]=> string(0) "" 
            } 
            ["title"]=> string(0) "" 
            ["url"]=> string(0) "" 
            ["description"]=> string(0) "" 
            ["thumbnail"]=> array(1) { 
                ["url"]=> string(0) "" 
            } 
            ["image"]=> array(1) { 
                ["url"]=> string(0) "" 
            } 
            ["footer"]=> array(2) { 
                ["text"]=> string(0) "" 
                ["icon_url"]=> string(0) "" 
            } 
        } 
    } 
}

Which in turn in the json script echo $json_data = json_encode($data_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);:

{"username":"DS_Announcer","avatar_url":"","tts":"false","content":"test","file":"","type":"rich","embeds":[{"author":{"name":"","url":"","icon_url":""},"title":"","url":"","description":"","thumbnail":{"url":""},"image":{"url":""},"footer":{"text":"","icon_url":""}}]}{"embeds": ["0"]}

Readable:

{
  "username":"DS_Announcer",
  "avatar_url":"",
  "tts":"false",
  "content":"test",
  "file":"",
  "type":"rich",
  "embeds":[
    {
      "author":{
        "name":"",
        "url":"",
        "icon_url":""
      },
      "title":"",
      "url":"",
      "description":"",
      "thumbnail":{
        "url":""
      },
      "image":{
        "url":""
      },
      "footer":{
        "text":"",
        "icon_url":""
      }
    }
  ]
}{"embeds": ["0"]}

"{"embeds": ["0"]}" is not there when everything is working OR I have embed inputs filled

The values I have set in this example are:

  • "username" => "DS_Announcer"
  • "content" => "test"
  • "type" => "rich"

The goal in this thread is to figure out a way to make it so the if statements determine if even the key will be added to the array. As it stands now, if statements add the key with a null value that makes it so the json script being encoded cannot be read by the application reading it (Which I'm sure most have already noticed it's a custom discord webhook api).

I appreciate any help in the matter.

答案1

得分: 2

如果您只想删除空值,可以递归遍历数组并取消设置这些值。

$array = [
    "username" => "DS_Announcer",
    "avatar_url" => "",
    "tts" => "false",
    "content" => "test",
    "file" => "",
    "type" => "rich",
    "embeds" => [
        [
            "author" => [
                "name" => "alex",
                "url" => "",
                "icon_url" => ""
            ],
            "title" => "",
            "url" => "",
            "description" => "",
            "thumbnail" => [
                "url" => ""
            ],
            "image" => [
                "url" => ""
            ],
            "footer" => [
                "text" => "",
                "icon_url" => ""
            ]
        ]
    ]
];

// 递归删除具有空值的键的函数
function removeEmptyKeys(&$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            removeEmptyKeys($value);
            if (empty($value)) {
                unset($array[$key]);
            }
        } elseif (empty($value)) {
            unset($array[$key]);
        }
    }
}

removeEmptyKeys($array);

$json = json_encode($array); // 将等于 {"username":"DS_Announcer","tts":"false","content":"test","type":"rich","embeds":[{"author":{"name":"alex"}}]}
英文:

If you want to remove only empty values, you can go recursevly trough the array and unset the values

$array = [
    "username" => "DS_Announcer",
    "avatar_url" => "",
    "tts" => "false",
    "content" => "test",
    "file" => "",
    "type" => "rich",
    "embeds" => [
        [
            "author" => [
                "name" => "alex",
                "url" => "",
                "icon_url" => ""
            ],
            "title" => "",
            "url" => "",
            "description" => "",
            "thumbnail" => [
                "url" => ""
            ],
            "image" => [
                "url" => ""
            ],
            "footer" => [
                "text" => "",
                "icon_url" => ""
            ]
        ]
    ]
];

// Function to recursively remove keys with null values
function removeEmptyKeys(&$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            removeNullKeys($value);
            if (empty($value)) {
                unset($array[$key]);
            }
        } elseif (empty($value)) {
            unset($array[$key]);
        }
    }
}

removeEmptyKeys($array);

$json = json_encode($array); // will equal {"username":"DS_Announcer","tts":"false","content":"test","type":"rich","embeds":[{"author":{"name":"alex"}}]}

答案2

得分: -1

查看 $_POST 数组的内容并将其打印出来。你可能会发现所有的键都存在,但值为空(因为你是从表单中提交的)。因此不仅要测试键是否存在,还要测试值是否存在。如果值为空,则不添加。

英文:

Check the content of the $_POST array by printing it. You'll probably find that all the keys exist, but with empty values (as you post it from a form). So don't just test for the keys to exists, test for the values as well. If 'empty', then do not add.

huangapple
  • 本文由 发表于 2023年6月27日 17:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定