z0mbieKale
z0mbieKale

Reputation: 1028

How to match a value in json file with PHP

I am saving data in JSON file for retrieving after redirect. If I check if the value matches in the json array, I always get false and something must be wrong, but I cannot figure it out. How can I the object with the specific SSL_SESSION_ID

Here's my json

[
    {
        "SSL_CLIENT_S_DN_CN": "John,Doe,12345678912",
        "SSL_CLIENT_S_DN_G": "JOHN",
        "SSL_CLIENT_S_DN_S": "DOE",
        "SSL_CLIENT_VERIFY": "SUCCESS",
        "SSL_SESSION_ID": "365cb4834f9d7b3d53a3c8b2eba55a49d5cac0112994fff95c690b9079d810af"
    },
    {
        "SSL_CLIENT_S_DN_CN": "John,Doe,12345678912",
        "SSL_CLIENT_S_DN_G": "JOHN",
        "SSL_CLIENT_S_DN_S": "DOE",
        "SSL_CLIENT_VERIFY": "SUCCESS",
        "SSL_SESSION_ID": "e7bd2b6cd3db89e2d6fad5e810652f2ae087965e64b565ec8933b1a67120b0ac"
    }
]

Here's my PHP script, which always returns It doesn't match

            $sslData     = Storage::disk('private')->get('ssl_login.json');
            $decodedData = json_decode($sslData, true);
            foreach ($decodedData as $key => $items) {

                if ($items['SSL_SESSION_ID'] === $SSL_SESSION_ID) {
                    dd("It matches");


                } else {
                    dd("It doesn't match");

                }
            }

Upvotes: 1

Views: 721

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

Your script will always end after the first iteration, since you're using dd() regardless if it was a match or not and you will always get the "no-match"-message if the first iteration isn't a match.

You should iterate through all the items and then see if there was a match or not:

$match = null;
foreach ($decodedData as $key => $items) {
    if ($items['SSL_SESSION_ID'] === $SSL_SESSION_ID) {
        $match = $items;
        // We found a match so let's break the loop
        break;
    }
}

if (!$match) {
    dd('No match found');
}

dd('Match found');

That will also save the matching item in the $match variable if you need to use the data somehow.

Upvotes: 3

Related Questions