Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php convert multidimensional array to json object

PHP NEWBIE
[PHP 7.4]

I am trying to refactor some old code.

GOAL: The two JSON must match.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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,
    ];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading