2

I know there are like hundreds similar questions on this site, but I just can't get my code working...

I have this JSON

{
"version":"1.0.0",
"buildDate":20131029,
"buildTime":165127,

"lockPath":"..\\var\\lock",
"scriptPath":"..\\var\\lock",
"connections":
[
{
    "name":"o016561",
    "bez":"GEW-NRW",
    "type":"OVPN"
},
{
    "name":"o016482",
    "bez":"GEW-BW",
    "type":"OVPN"
},
{
    "name":"o019998",
    "bez":"GEW-SH",
    "type":"OVPN"
}
]}

how can I access the "name" values to check if there's an existing file with an equal name? I tried

$json_config_data = json_decode(file_get_contents($json_path,true));

    foreach($json_config_data->connections as $connectionName)
    {
        if($connectionName->name == $fileName)
        {
            $status = 1;
        }
        else
        {
            $status = 0;
        }
    }

but I always get $status = 0... I think there's an easy solution for this, but I'm pretty new to PHP so I'd be glad for any kind of help. Thanks in advice

2 Answers 2

5

You're resetting the value of $status for every iteration which means that the last connection HAS to be the correct one. You're probably looking for a break statement.

$json_config_data = json_decode(file_get_contents($json_path,true));

$status = 0; //Default to 0
foreach($json_config_data->connections as $connectionName)
{
    if($connectionName->name == $fileName)
    {
        $status = 1;
        break; //End the loop
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

after reading your post, it all makes sense now. thanks a lot!
2

This would only result in $status == 1 if the final name matched your requirements; otherwise you're setting $status back to 0. You should break out of the loop when you find a match:

$status = 0;

foreach ($json_config_data->connections as $connectionName) {
    if ($connectionName->name == $fileName) {
        $status = 1;
        break; // this breaks out of the foreach loop
    }
}

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.