简体   繁体   中英

How to combine foreach and json_decode in PHP?

I have an simple JSON file (KironDevCoder.json) :

{
  "username":"KironDevCoder",
  "password":"5UD2537AD00FB1E4B3361ABAA593C860738G6K1E828E6C88417C202BF98A1FDD8E56F71B707491U",
  "rank":"Admin"
}

When I do

$jsonCode = json_decode(file_get_contents("KironDevCoder.json"))
foreach ($jsonCode as $x) {
  echo $x."<br>";
}

But then I get:

KironDevCoder
5UD2537AD00FB1E4B3361ABAA593C860738G6K1E828E6C88417C202BF98A1FDD8E56F71B707491U
Admin

But how do I then get:

username
password
rank

I know that it isn't needed for this example, but I have the same problem with an file where it is needed.

foreach can loop over the key and value of an associative array:

foreach( $jsonCode as $k => $v )

Given the above example, $k will hold the key of your JSON structure (ie username , password , etc.) and $v will hold the actual value ( KironDevCoder , etc.). So you can loop through as follows:

foreach( $jsonCode as $k => $v )
{
    echo $k.'<br />';
}

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