Extracting Data from JSON Using PHP
Here's a test jason feed
{"MEMBERS":[{"NAME":"Joe Bob","PET":["DOG"]}, {"NAME":"Jack Wu","PET":["CAT","DOG","FISH"]}, {"NAME":"Nancy Frank","PET":["FISH"]}]}
开发者_StackOverflow社区
What I'm attempting to do is extract data if PET contains CAT or FISH or both. Another user suggested a filter as such:
$filter = array('CAT', 'FISH');
// curl gets the json data (this part works fine but is not shown for brevity)
$JSONarray=json_decode($JSONdata,true);
foreach($JSONarray['MEMBERS'] as $p) {
if (in_array($p['PET'], $filter)) {
echo $p['NAME'] . '</br>';
}
}
But it's not returning anything.
Note: edited based on comments below
Use strings to access the array and not uninitialized constants.
$p['PET']
is an array. You have to use some other method to compare it against$filter
, e.g.array_intersect
:foreach($JSONarray['MEMBERS'] as $p) { $diff = array_intersect($filter, $p['PET']); if (!empty($diff)) { echo $p['NAME'].'</br>'; } }
DEMO
It should work like this:
foreach($JSONarray['MEMBERS'] as $p) {
if (array_diff($p['PET'], $filter) != $p['PET']) {
echo $p['NAME'].'</br>';
}
}
Remember to always use quotes when you are trying to access an element of an associative array. Without quotes, PHP tries to interpret it as a constant (throwing a Notice on failure). So instead of
$a[index]
do$a['index']
. Please also see Why is $foo[bar] wrong?In your code,
$p['PET']
will be an array of pet names, not one pet name. Testing within_array()
won't be successful, because it will try to find the whole array in$filter
. In my code example, I usedarray_diff()
which will find the difference between the two arrays, then I compare it to the original array. If they match, the$filter
pets were not found.
First, you need to use quotes on your array keys:
$JSONarray['MEMBERS']
$p['PET']
$p['NAME']
Secondly, you can't use in_array as it assumes 'needle' to be the array('CAT', 'FISH') and not any one of it's values. (The parameter order was also the other way around)
Here's a method using array_intersect:
foreach($JSONarray['MEMBERS'] as $p) {
$test = array_intersect($filter, $p['PET']);
if (count($test)>0) {
print( $p['NAME'].'</br>' );
}
}
精彩评论