我试图解析一个看起来像这样的JSON文件,
[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]
我试图从名为desc
的数组中获取Development Task
对象,系统需要是动态的,所以我不能只使用json_o[0](desc);
我尝试了不同的方法,例如多次预测数据,但我仍然无法想到解决方案,任何帮助都会很棒,欢呼。
答案 0 :(得分:1)
试试这个:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]';
$encoded = json_decode($jsonData);
foreach($encoded as $data)
{
if('Development Task' == $data->name)
{
echo $data->desc;
}
}
答案 1 :(得分:0)
如果您搜索动态字段,我会选择:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "FirstDescription",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "SecondDescription",
"url": ""
}
]';
$arrayFromJson = json_decode($jsonData, true);
function searchByKey($keyToSearchIn, $searchName, $array) {
foreach ($array as $key => $val) {
if ($val[$keyToSearchIn] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByKey("name", "Development Task", $arrayFromJson);
所以
var_dump($return);
返回
string(16) "FirstDescription"
注意:如果您只需按名称搜索,则可以使用以下命令更改功能:
function searchByName( $searchName, $array) {
foreach ($array as $key => $val) {
if ($val['name'] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByName("Development Task", $arrayFromJson);
希望它有所帮助。
答案 2 :(得分:0)
代码中的注释解释了会发生什么:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "moocow",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "wowcow",
"url": ""
},
{
"id": "539eebe09rb42c971d46b9ba1",
"name": "Development Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "sowccow",
"url": ""
}
]';
$encoded = json_decode($jsonData, true); //converts the json object to an array
foreach ($encoded as $arrayObject){
if( in_array("Development Task", $arrayObject) ){
print_r($arrayObject['desc'] . "\n");
}
}
-> moocow sowccow
基于
我正在尝试从名为Development Task
的数组中获取desc对象
这应该做你想要的,你可以轻松地获取字符串并使其成为变量。 PHP.net上有很多内置函数可以调整,并且可能比滚动自己的代码好10倍。