简体   繁体   English

多级数组使用php从json文件中获取准确值

[英]multilevel array get exact value from json file using php

i have htis json file: 我有htis json文件:

{
    "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: 在我的PHP代码中,我这样读:

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

and i would like to access values by "kod" value. 我想通过“ kod”值访问值。 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”值:

$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. 在上面的示例中,由于键是字符串,因此您尝试使用[nazwa]进行访问时应使用["nazwa"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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