Search code examples
phparraysjsonforeachkey

how to get json key value in php?


How do I get all of the keys value in this JSON with PHP? my php code is:

<?php 
$json = json_decode('{
    "data": {
        "after": [{
            "google.com": "35"
        }, {
            "yahoo.com": "10"
        }, {
            "worldi.ir": "30"
        }, {
            "cnn.com": "554"
        }, {
            "scio.ir": "887"
        }],
        "before": [{
            "bbc.com": "44"
        }, {
            "rtl.com": "15"
        }, {
            "quran.com": "9"
        }, {
            "lap.com": "12"
        }, {
            "search.com": "13"
        }]
    }
}');
foreach($json->data->after as $key => $value) {
    echo "$key<br/>";
    foreach(((array)$json->data->after)[$key] as $val) {
        echo "$val<br/>";
    }
}
?>

results

0
35
1
10
2
30
3
554
4
887

don't show key value. i want get all key value.such as google.com, yahoo.com, worldi.ir cnn.com, and ...


Solution

  • after is an array, so the $key returned in the outer foreach loop is just an index (an integer). You should include $key => $value again in your second foreach to get the key of each inner object. Further, you can just use a foreach on the $value of your first foreach. You don't have to specify the whole key path down to it again.

    <?php 
    $json = json_decode('{
        "data": {
            "after": [{
                "google.com": "35"
            }, {
                "yahoo.com": "10"
            }, {
                "worldi.ir": "30"
            }, {
                "cnn.com": "554"
            }, {
                "scio.ir": "887"
            }],
            "before": [{
                "bbc.com": "44"
            }, {
                "rtl.com": "15"
            }, {
                "quran.com": "9"
            }, {
                "lap.com": "12"
            }, {
                "search.com": "13"
            }]
        }
    }');
    foreach($json->data->after as $key => $value) {
        foreach($value as $k => $val) {
            echo "$k<br/>$val<br/>";
        }
    }
    ?>