简体   繁体   中英

PHP foreach loop JSON

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM