0

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.

4
  • {"embeds": ["0"]} is not coming from the code you posted. You're only echoing one JSON object, but your output has two. Commented Jun 27, 2023 at 9:14
  • I do believe it's coming from the return of the json_encode() function. Commented Jun 27, 2023 at 9:15
  • It's coming from some other json_encode(), not this one. Commented Jun 27, 2023 at 9:16
  • It is impossible for one single json_encode call to give a result in the form {}{} - because that is not even valid JSON. If you had multiple objects in an array, then the result would have the form [{},{}]. The only logical conclusion for with result you have shown, is that this is the result from two json_encode calls, output directly one after the other. Commented Jun 27, 2023 at 10:05

2 Answers 2

2

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"}}]}

Sign up to request clarification or add additional context in comments.

2 Comments

I'll give it a shot. I did at one point try using unset($data_arr["key"]) as the else condition, which didn't do anything.
Worked like a charm! Must appreciated. little edit for if anyone stumbles upon the same issue: Typo in the function -> (line 5 of function) removeNullKeys($value); => removeEmptyKeys($value);
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.