[英]Add Key to Value in JSON with PHP
我正在使用的 API 格式化其 JSON,而没有对象值的KEY
。 它的格式更像是一个数组。 作为参考,这是我尝试使用的 API 的链接https://opensky-network.org/apidoc/rest.html 。 下面是 JSON 的示例。
错误的例子
{
"time": 1535758880,
"states": [
[
"First",
"A"
],
[
"Second",
"B"
]
]
}
上面的 JSON 也有每个对象的方括号。 这在我的情况下不起作用。 它们需要是大括号。 下面是我试图实现的一个例子。 请注意,对象括号是卷曲的,并且每个值都有一个键。
需要的例子
{
"time": 1535758880,
"states": [
{
"id": "First",
"content": "A"
},
{
"id": "Second",
"content": "B"
}
]
}
这是我目前正在编写的用于在 JSON 中查找值的代码。
<?php
$str = '
{
"time": 1535758880,
"states": [
{
"id": "First" ,
"content": "A"
},
{
"id": "Second" ,
"content": "B"
}
]
}';
$json = json_decode($str);
foreach($json->states as $item)
{
if($item->id == "Second")
{
echo $item->content;
}
}
?>
我的总体问题是,如何将id
和content
添加到我的 JSON 并用大括号替换每个对象的方括号? 我想我需要以某种方式做一个 str_replace() 。 但我不确定如何处理这个问题。
您需要重新转换数组,然后将其重新编码回 json。 像这样的东西:
$formatted = json_decode($str);
foreach ($formatted->states as $key => $value) {
$tmp = array(
'id' => $value[0],
'content' => $value[1]
);
$formatted->states[$key] = $tmp;
}
// If you want this in array format you are done here, just use $formatted.
// If you want this back in json format, then json_encode it.
$str = json_encode($formatted);
绝对不要尝试字符串替换。
首先,我会质疑您是否真的需要从数组到对象的转换。 $item[0]
并不比$item->id
差多少。 如果你真的想要,你可以让你的代码更明显,并为索引创建变量。
$id = 0;
$content = 1;
if ($item[$id] == 'Second') {
echo $item[$content];
}
但是,如果由于某种原因您不得不转换,您可以使用上面的 mopsyd 帖子中的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.