简体   繁体   中英

multilevel array get exact value from json file using php

i have htis json file:

{
    "waluta": "EUR",
    "vat": 1,
    "01_00101": {
        "cena": 130.8,
        "kod": "00101",
        "nazwa": "Span TRICK 1200/1982-ABS",
        "powiazanyZ": "00139"
    },
    "01_00102": {
        "cena": 125.86,
        "kod": "00102",
        "nazwa": "Span TRICK 1200/1864-ABS",
        "powiazanyZ": "00140"
    },
    "02_00122": {
        "cena": 0,
        "kod": "00122",
        "nazwa": "SET to Wicket TRICK 1200 elektrolock RIGHT",
        "powiazanyZ": "00000"
    },
    "02_00123": {
        "cena": 0,
        "kod": "00123",
        "nazwa": "SET to Wicket TRICK 1200 elektrolock LEFT",
        "powiazanyZ": "00000"
    },
    "02_00152": {
        "cena": 0,
        "kod": "00115",
        "nazwa": "Gate ABS 1200/3070 prepared to servomotor ARM 400",
        "powiazanyZ": "00138"
    },
    "02_00138": {
        "cena": 0,
        "kod": "00115",
        "nazwa": "Gate ABS 1200/3070 handle, bolt",
        "powiazanyZ": "00152"
    }
}

and in my php code i read this like this:

$string = file_get_contents("cennik-en.json");
$cennik_a=json_decode($string,true);

and i would like to access values by "kod" value. is this possible? because by key value i think i can do like that:

$json_a['01_00101'][nazwa];
function returnMainKey( $json, $kod) {
    foreach( $json as $key => $value)
        if( is_array( $value))
            if( isset( $value["kod"]) && $value["kod"] == $kod)
                return $key;
    return null;
}

$string = file_get_contents("cennik-en.json");
$cennik_a=json_decode($string,true);
$key = returnMainKey( $cennik_a, "00101");
echo $cennik_a[$key]["nazwa"];

You should be able to get the "kod" value like so:

$kod = $json_a['01_00101']["kod"];

In your example above, you're trying to access with [nazwa] when it should be ["nazwa"] as the keys are strings.

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