我试图迭代文件https://alexa.rob-balmbra.co.uk/tracker/mapping.json
我试图在" 4-72"中尝试遍历每个名称,但我想访问其内容及其名称。
我正在对其内容进行搜索,当我匹配代码时,我需要随后获取密钥,如' 4-72'等...
每次使用foreach时,我都会获取json文件的内容,而不是密钥和内容。
答案 0 :(得分:1)
//Fetch the JSON file and decode it into an associative array
$json = json_decode( file_get_contents('https://alexa.rob-balmbra.co.uk/tracker/mapping.json'), true );
//This is the code you want to search for
$searchCode = "03013";
//Loop through the json array, get key and data
foreach($json as $key=>$data){
//If the code matches what you're searching for, echo the key out and move past the foreach loop.
if($data["code"] == $searchCode){
echo "The service name is: " . $key;
break;
}
}
//You don't need this here. I just used it so I could see all the codes.
echo '<pre>' . print_r($json, 1) . '</pre>';
代码说明:
答案 1 :(得分:0)
每次使用foreach时,我都会获取json文件的内容,而不是密钥和内容。
您是否已将JSON字符串转换为数组?
$jsonValues = json_decode($jsonString,true) ;
foreach($jsonValues as $key=>$data) {
// do your thing here
}