Ive got the following JSON:
{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}
I also have another JSON that gives me the ID I want to search for. For example: "d671ac7d-3b5a-4777-8510-6e8e58295061".
I want to search for the JSON Object, that contains that ID and get the value of the name key. I tried with loops and if, else's but I didn't manage to get it working.
Thanks for your help!
CodePudding user response:
decode the json as array object then loop through with the ID that u want to search
<?php
$json = '{
"servers": [
{
"id": "f34c0185-4c9e-40fd-82f6-1d6e9a5d499e",
"name": "vm01"
},
{
"id": "d671ac7d-3b5a-4777-8510-6e8e58295061",
"name": "vm02"
},
{
"id": "h59j23cc-9ve2-4508-1277-85y1lo27562m",
"name": "vm03"
}
]
}';
$j = json_decode($json, true);
foreach($j['servers'] as $arr)
{
if( $arr['id'] == 'd671ac7d-3b5a-4777-8510-6e8e58295061' ) echo $arr['name'];
}
demo: https://3v4l.org/0DboX