gpt4 book ai didi

php - 如何在 PHP 中解码具有多个对象的 JSON 字符串?

转载 作者:IT王子 更新时间:2023-10-29 00:11:16 25 4
gpt4 key购买 nike

在您的帮助下,我知道如何用一个对象解码 JSON 字符串 How to decode a JSON String

但现在我想用几个对象改进解码 JSON 字符串,但我不明白该怎么做。

这是一个例子:

{ "inbox": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"sent": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"draft": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
  1. 如何只用一个 foreach() 来解码上面的 JSON 字符串?
  2. 如何检测对象的名称:收件箱,在这个 foreach() 上发送或草稿?

最佳答案

新答案

关于您修改后的问题:foreach 实际上适用于属性以及多值项(数组),details here .因此,例如,在您的问题中使用 JSON 字符串:

$data = json_decode($json);
foreach ($data as $name => $value) {
// This will loop three times:
// $name = inbox
// $name = sent
// $name = draft
// ...with $value as the value of that property
}

在属性的主循环中,您可以使用内部循环遍历每个属性指向的数组条目。因此,例如,如果您知道每个顶级属性都有一个数组值,并且每个数组条目都有一个“firstName”属性,则此代码:

$data = json_decode($json);
foreach ($data as $name => $value) {
echo $name . ':'
foreach ($value as $entry) {
echo ' ' . $entry->firstName;
}
}

...将显示:

inbox:  Brett  Jason  Elliottesent:  Issac  Tad  Frankdraft:  Eric  Sergei

Old answer(s)

Begin editRe your comment:

Now I would like to know how to decode JSON string with several objects!

The example you posted does have several objects, they're just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:

{"name": "I'm the first object"},
{"name": "I'm the second object"}

该 JSON 无效。 必须 有一个顶级对象。它可能只包含一个数组:

{"objects": [
{"name": "I'm the first object"},
{"name": "I'm the second object"}
]}

...或者您当然可以为各个对象命名:

{
"obj0": {"name": "I'm the first object"},
"obj1": {"name": "I'm the second object"}
}

结束编辑

您的示例是一个包含三个属性的对象,每个属性的值都是一个对象数组。事实上,它与您链接的问题中的示例没有太大区别(它也有一个具有数组值属性的对象)。

所以:

$data = json_decode($json);
foreach ($data->programmers as $programmer) {
// ...use $programmer for something...
}
foreach ($data->authors as $author) {
// ...use $author for something...
}
foreach ($data->musicians as $musician) {
// ...use $musician for something...
}

关于php - 如何在 PHP 中解码具有多个对象的 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2560096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com