我正在尝试接受我的JSON输入并生成一个简单的数组来搜索,但据我所知,这给我带来了一些麻烦。
首先,这是我的JSON,从文件加载:
{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}
有没有办法简化这个或最小化数组?
我一直在使用以下代码来预览我的数组,但我试图让它搜索id,然后打印id,boat和name的值。
$json_url = "teams.json";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>';
print_r($data);
echo '</pre>';
答案 0 :(得分:0)
这真的很简单。没有必要将一个完美的好对象转换为一个数组,它只会让生活变得更复杂。
您的数据结构中唯一的数组是teams
数组,可以像这样轻松处理
$json = '{
"teams": [
{
"id": "1",
"boat": "Test",
"name": "Palle Test"
},
{
"id": "2",
"boat": "Test 2",
"name": "Name Test 2"
},
{
"id": "3",
"boat": "Test 3",
"name": "Name Test 3"
},
{
"id": "4",
"boat": "Test 4",
"name": "mller"
}
]
}';
$data = json_decode($json);
//print_r($data);
foreach ($data->teams as $object) {
if ( $object->id == 2) {
echo 'boat is ' . $object->boat . ' and name is ' . $object->name . PHP_EOL;
}
}
以上示例的结果将是
boat is Test 2 and name is Name Test 2