如何使用动态更改的键值访问嵌套的JSON对象

I'm trying to get JSON data into my PHP script and the problem is that this is a nested JSON object with dynamically changed key value (I've converted JSON objects into PHP objects):

stdClass Object
(
    [665261] => stdClass Object
        (
            [id] => 665261
            [SpeiseplanName] => Campus Mensa Wismar
            [Datum] => 2019-07-12
            [KstNr] => 462
            [ArtikelText] => ein Brathering ohne Mittelgräte
            [ZusatzStoffe] => 9 Fi Gl
            [ZusatzStoffeText] => mit Süßungsmittel, Fische, Gluten
            [PeStud] => 0.75
            [PeBed] => 1.35
            [PeGast] => 1.75
            [sortierung] => 46
        )

    [665262] => stdClass Object
        (
            [id] => 665262
            [SpeiseplanName] => Campus Mensa Wismar
            [Datum] => 2019-07-12
            [KstNr] => 462
            [ArtikelText] => zwei Bratheringe ohne Mittelgräte
            [ZusatzStoffe] => 9 Fi Gl
            [ZusatzStoffeText] => mit Süßungsmittel, Fische, Gluten
            [PeStud] => 1.25
            [PeBed] => 1.9
            [PeGast] => 2.25
            [sortierung] => 47
        )

    [665263] and so on.

So, I've already get the data like this:

<p id="desc"><?= htmlReady(_($data[665261]['ArtikelText'])) ?></p>

The output was then "zwei Bratheringe ohne Mittelgräte" as expected. But this numeric key 665261 is dynamic and changed every day.

So how can I access date with key's values like this? Thank you for your help.

douqiaolong0528
douqiaolong0528 我想迭代所有对象并输出一些值但不是全部。
大约一年之前 回复
dszdiavv474681
dszdiavv474681 你有一组对象(或对象的对象),你想访问第一个对象还是迭代所有对象并输出每个对象的单个值?
大约一年之前 回复

2个回答

You just need to use foreach loop, like this:

Suppose your object of objects name is $objects:

foreach ($objects as $obj) {
    echo '<p id="desc">' . htmlReady(_($obj->ArtikelText)) . '</p>';
}

Or if you have a array of arrays, with the name of $arrays:

foreach ($arrays as $arr) {
    echo '<p id="desc">' . htmlReady(_($arr['ArtikelText'])) . '</p>';
}
douda5227
douda5227 你想过滤掉什么? 并取决于哪个属性?
大约一年之前 回复
dongxian1921
dongxian1921 不,它不起作用。 它说“未定义的索引”。
大约一年之前 回复
dpdfh60088
dpdfh60088 在循环中添加if语句以过滤掉输出
大约一年之前 回复
dongpin1850
dongpin1850 谢谢。 但是,如果我不需要所有的对象呢?
大约一年之前 回复

First of all you need to check if the Key exists in your array. If it exists then you need to fetch the object corresponding to that key. Afterwards you can print any variable you need in the object.

Let us say that your main object is $objects and the key you are looking for is $key. You can use following code then.


if( isset( $objects->$key ) ) {  
    $innerObject = $objects->$key;
    echo $innerObject->ArtikelText; //prints ein Brathering ohne Mittelgräte
    echo $innerObject->PeStud; // prints 0.75
}

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐