我有一个PHP脚本几乎可以完成我想要的所有操作。我从API中提取了一些信息并准备了一份CSV文档 - 文档创建得很好,但是有几列是空白的,我不知道如何从对象中调用它们(stdClass)我是进入我的vardump。我试图从下面的每个numkey对象中获取以下索引:
我真的在努力解决我的解码JSON的var_dump问题。以下是来自相关API的JSON响应:
{
"623587": {
"caption": "",
"created_at": "2015-06-30T17:59:24+00:00",
"deleted": "0",
"id": "623587",
"links": {
"VariantCustomIds": [
{
"id": "108601807"
}
]
},
"name": "SKU",
"updated_at": "2015-06-30T17:59:24+00:00"
},
"840664": {
"caption": "",
"created_at": "2015-09-21T15:04:18+00:00",
"deleted": "0",
"id": "840664",
"links": {
"VariantCustomIds": [
{
"id": "144012064"
}
]
},
"name": "Headband Style",
"updated_at": "2015-09-21T15:04:18+00:00"
},
"840684": {
"caption": "",
"created_at": "2015-09-21T15:04:18+00:00",
"deleted": "0",
"id": "840684",
"links": {
"VariantCustomIds": [
{
"id": "144012074"
}
]
},
"name": "Ink Type",
"updated_at": "2015-09-21T15:04:18+00:00"
},
"840694": {
"caption": "",
"created_at": "2015-09-21T15:04:18+00:00",
"deleted": "0",
"id": "840694",
"links": {
"VariantCustomIds": [
{
"id": "144012084"
}
]
},
"name": "Fabric Type",
"updated_at": "2015-09-21T15:04:18+00:00"
}
}
我通过PHP中的json_decode函数传递它,这是我得到的var_dump:
object(stdClass)#1308 (1) { ["623587"]=> object(stdClass)#1310 (7) { ["caption"]=> string(0) "" ["created_at"]=> string(25) "2015-06-30T17:59:24+00:00" ["deleted"]=> string(1) "0" ["id"]=> string(6) "623587" ["links"]=> object(stdClass)#1309 (1) { ["VariantCustomIds"]=> array(1) { [0]=> object(stdClass)#1303 (1) { ["id"]=> string(9) "108601798" } } } ["name"]=> string(3) "SKU" ["updated_at"]=> string(25) "2015-06-30T17:59:24+00:00" } }
我已经尝试过为每个循环做一个,但是当我这样做时只有一个对象。我尝试过调用$ myVariable-> id,$ myVariable-> links和$ myVariable-> name。当我通过var_dump()传递它们时,所有这些都返回NULL。
任何帮助都会非常感激。
答案 0 :(得分:4)
只需按下括号/大括号,记住在JS中,{}
是一个对象,而[]
是一个数组:
json = {
| | "623587": {
| | | "caption": "",
| | | "created_at": "2015-06-30T17:59:24+00:00",
| | | "deleted": "0",
| | | "id": "623587",
| | | "links": {
| | | | | "VariantCustomIds": [
| | | | | | | {
| | | | | | | | "id": "108601807"
| | | | | | | | |
$obj -> 623587 -> links -> variantcustomids [0] -> id
所以你的最终PHP路径,使用适当的访问方法和大写
$obj[623587]->links->VariantCustomIds[0]->id
答案 1 :(得分:1)
看看json_decode documentation。有第二个(optinal)参数告诉json_decode返回asoc数组。所以你的代码应该是这样的:
$decoded = json_decode($jsonString, true);
答案 2 :(得分:1)
我知道,你已经解决了。但你也可以去StdClass对象方法:
<?php
$sample = file_get_contents('http://host/api/sample.json');
$data = json_decode($sample);
foreach ($data as $id => $object) {
$name = $object->name;
$id = $object->links->VariantCustomIds[0]->id; #OR $id = $id
$updated_at = $object->updated_at;
}