Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON get key and value

Tags:

json

php

I have the following JSON format:

{
    "S01": ["001.cbf", "002.cbf", "003.cbf", "004.cbf", "005.cbf", "006.cbf", "007.cbf", "008.cbf", "009.cbf"],
    "S02": ["001.sda", "002.sda", "003.sda"],
    "S03": ["001.klm", "002.klm"]
}

I try using this code:

$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');

foreach($json as $key => $val) {
     if ($key) { echo 'KEY IS: '.$key; };
     if ($val) { echo 'VALUE IS: '.$value; };
     echo '<br>';
}

But i got empty results...i need to get output like this:

KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf

KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda

KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klm

This i need so that i can generate ul and li elements using value and key name...this is JSON format that is stored in mysql database and is read to php script that needs to parse the JSON in the above output so that i can create ul and li elements using output.

I try to do foreach but i got empty results? I know when i got value that i need to do explode string using explode(', ', $value) but i can't get $value and $key to be read as needed in PHP.

like image 410
Igor Petev Avatar asked Dec 03 '22 20:12

Igor Petev


1 Answers

This solves your problem, you had to cast $json to array because it was considered as an stdClass object ;)

<?php 
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
    echo "KEY IS: $key<br/>";
    foreach(((array)$json)[$key] as $val2) {
        echo "VALUE IS: $val2<br/>";
    }
}
?>

Try It Online!

I recommend you to use the function var_dump($var) next time you run into troubles, it will help you to figure out what's wrong.

like image 93
txemsukr Avatar answered Dec 06 '22 09:12

txemsukr