这种类型的数组的正确名称是什么?
有3个主要部分和4个子部分由“issuedTime”“text”“url”和“validToTime”组成,你如何开始将其转换为对象?如果只有1个主要部分,那么使用3个主要部分会相当简单,并且每个主要部分没有任何标识让我摸不着头脑从哪里开始。
任何建议都表示赞赏。
[{
"issuedTime":"7:13pm Sunday 13 June 2010",
"text":"\nAmended 7:10pm.\n\nText text and more text\n",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00am Monday 14 June 2010"
},{
"issuedTime":"8:33pm Sunday 13 June 2010",
"text":"\nText and more text.\n",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00pm Monday 14 June 2010"
},{
"issuedTime":"10:40am Sunday 13 June 2010",
"text":"\nAnd even more text.",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00am Tuesday 15 June 2010"
}
]
答案 0 :(得分:10)
JSON (an acronym for JavaScript Object Notation) 是基于文字的轻量级广告 开放式标准设计 人类可读的数据交换。它是 源自JavaScript 用于表示的编程语言 简单的数据结构和关联 数组,称为对象。尽管如此 与JavaScript的关系,它是 与语言无关,具有解析器 适用于几乎所有人 编程语言。
您可以使用 json_decode
函数轻松将其转换为php数组,以下是php网站的示例:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
<强>结果:强>
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
json_decode
的第二个参数是它是否应该转换为关联数组。如果未指定第二个参数,则输出将如下:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
因此,您可以将其转换为数组并循环遍历它:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array = json_decode($json, true);
print_r($array);
foreach($array as $key => $value)
{
// manipulate the var $value
}
答案 1 :(得分:2)
以下是解析json的方法
<?php
$json = '[{
"issuedTime":"7:13pm Sunday 13 June 2010",
"text":"\nAmended 7:10pm.\n\nText text and more text\n",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00am Monday 14 June 2010"
},{
"issuedTime":"8:33pm Sunday 13 June 2010",
"text":"\nText and more text.\n",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00pm Monday 14 June 2010"
},{
"issuedTime":"10:40am Sunday 13 June 2010",
"text":"\nAnd even more text.",
"url":"\/folder\/fc\/name.png",
"validToTime":"12:00am Tuesday 15 June 2010"
}]';
// Parse the json into a PHP array that holds multiple "stdClass Object"s
$obj = json_decode($json);
// Iterate through each "stdClass Object" and show what it contains
foreach($obj as $var => $value)
{
echo "Number: $var <br/>";
echo "Issued: " . $obj[$var]->issuedTime . "<br/>";
echo "Text: " . $obj[$var]->text . "<br/>";
echo "URL: " . $obj[$var]->url . "<br/>";
echo "Valid to: " . $obj[$var]->validToTime . "<br/>";
echo "<br/>";
}
?>
一旦你有了$ obj,就可以像上面的foreach循环那样访问它,或者访问,假设您要使用的第二个列表中的文本:
echo $obj[1]->text; // Second listing, since the first listing is $obj[0]
和HTML链接w文本相同:
echo '<a href="' . $obj[1]->url . '">' . $obj[1]->text . '</a>';
答案 2 :(得分:1)
你试过json_decode()吗?它应该正确地解析为stdObject
。
答案 3 :(得分:1)