I have following JSON:
我有以下JSON:
$p={
"main1" : [
{
"child1" : valueA,
"child2" : valueB,
"child3" : valueC,
},
{
"child1" : value1,
"child3" : value3,
},
],
"main2" : "valueMain2"
}
The element child2
has to be checked if it exists or not and then the value is taken. I am using json_decode:
必须检查元素child2是否存在,然后获取该值。我正在使用json_decode:
$response = json_decode($p,true);
How do I check if an element exists or not in PHP? Do I have to make separate function or is there built-in functionality?
如何在PHP中检查元素是否存在?我是否必须制作单独的功能或是否有内置功能?
3 个解决方案
#1
9
The same way you'd check if a key of any array exists:
以同样的方式检查是否存在任何数组的键:
with isset($array['key'])
or array_key_exists('key',$array)
.
with isset($ array ['key'])或array_key_exists('key',$ array)。
#2
1
Here's how I've been doing it.
这就是我一直在做的事情。
$child2exists = count($response['main1']['child2']);
If ($child2exists == 1)
{
echo "EXISTS";
}
else
{
echo "DOESNT EXIST";
}
Hope this helps.
希望这可以帮助。
#3
0
You can use the json decode as an object and check whatever exist:
您可以使用json decode作为对象并检查存在的内容:
$response = json_decode($p);
if (isset($response->main2)) {
echo $response->main2; // valueMain2
}
Also you can use a foreach to get the item list:
您还可以使用foreach获取项目列表:
foreach ($response->main1 as $item) {
echo $item->child1; // valueA value1
}
#1
9
The same way you'd check if a key of any array exists:
以同样的方式检查是否存在任何数组的键:
with isset($array['key'])
or array_key_exists('key',$array)
.
with isset($ array ['key'])或array_key_exists('key',$ array)。
#2
1
Here's how I've been doing it.
这就是我一直在做的事情。
$child2exists = count($response['main1']['child2']);
If ($child2exists == 1)
{
echo "EXISTS";
}
else
{
echo "DOESNT EXIST";
}
Hope this helps.
希望这可以帮助。
#3
0
You can use the json decode as an object and check whatever exist:
您可以使用json decode作为对象并检查存在的内容:
$response = json_decode($p);
if (isset($response->main2)) {
echo $response->main2; // valueMain2
}
Also you can use a foreach to get the item list:
您还可以使用foreach获取项目列表:
foreach ($response->main1 as $item) {
echo $item->child1; // valueA value1
}