0

PHP NEWBIE [PHP 7.4]

I am trying to refactor some old code.

GOAL: The two JSON must match.

Code snipppet 1: Old JSON code generated from php array

Code snippet 2: New JSON code generated from php array

Objective: Both must match, I am using php unit to compare them. For simplicity, I have removed the testing code.

PROBLEM: Extra set of square brackets, see image below.

I tried Using JSON_FORCE_OBJECT, which removes the square brackets, but introduces {... john: { "0": { "byEmail" ... " and ... "marie": { "1" { "byEmail" ...

(Naming wise: I have used John and marie, but these could be promotions, offers, packages, etc. so ignore the naming please)

SNIPPET 1 - php code


$body = [
            "data" => [
                "john" => [
                    "byEmail" => [
                        "status" => true,
                        "source" => "my-server",
                    ],
                    "byPhoneCall" => [
                        "status" => true,
                        "source" => "my-server",
                    ]
                ],
                "marie" => [
                    "byEmail" => [
                        "status" => true,
                        "source" => "my-server",
                    ],
                    "byPhoneCall" => [
                        "status" => true,
                        "source" => "my-server",
                    ]
                ]
            ]
        ];

This gets converted to this JSON object:

// SNIPPET 1 - running json_encode()
{
    "data": {
        "john": {
            "byEmail": {
                "source": "my-server",
                "status": true
            },
            "byPhoneCall": {
                "source": "my-server",
                "status": true
            }
        },
        "marie": {
            "byEmail": {
                "source": "my-server",
                "status": true
            },
            "byPhoneCall": {
                "source": "my-server",
                "status": true
            }
        }
    }
}

SNIPPET 2:

I am creating this data structure dynamically now, because future requirement may have johnByPost, johnByFax, etc.:

//my-file-dynamic-generation.php

public function constructArray($johnByEmail=null, $johnByPhone=null, $marieByEmail=null, $marieByPhone=null) {
        $body = [ "data" => ["john" => [], "marie" => []]];

        if ($johnByEmail !== null) {
            array_push($body["data"]["john"], $this->createKeyValuePair("byEmail", $johnByEmail));
        }

        if ($johnByPhone !== null) {
            array_push($body["data"]["john"], $this->createKeyValuePair("byPhoneCall", $johnByPhone));
        }

        if ($marieByEmail !== null) {
            array_push($body["data"]["marie"], $this->createKeyValuePair("byEmail", $marieByEmail));
        }

        if ($marieByPhone !== null) {
            array_push($body["data"]["marie"], $this->createKeyValuePair("byPhoneCall", $marieByPhone));
        }
        return $body;
    }


// HELPER func


function createKeyValuePair($title=null, $status=null, $source="my-server") {
        return [
            $title => [
                "status" => $status,
                "source" => $source,
                ]
            ];
    }

JSON - OUTPUT

Left: Snippet 1, Right: Snippet 2

I have tried to use json_encode($data, JSON_FORCE_OBJECT)

That resulted me to get an extra key, which I don't want (I got .... [0] => 'marie' => ... [1] => 'john'

Appreciate reading this, thanks!

1 Answer 1

1

You are creating a new array inside the function createKeyValuePair() (probably to add the key). You could use the function the create the content only, and create the key inside the function constructArray() :

$body["data"]["john"]["byEmail"] = $this->createKeyValuePair($johnByEmail);

and the function :

function createKeyValuePair($status = null, $source = "my-server"): array 
{
    return [
        "status" => $status,
        "source" => $source,
    ];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This solves the problem. Phew. As a php expert, would you be able to comment on my refactoring style? Is there a better way than I am doing things right now?
Difficult to say with a small piece of code (see also codereview - for working code). Just a tips : don't forget to add return type to function (ex here, : array) to enforce the data-type flow and avoid coding errors ;)

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.