从JSON使用PHP提取数据 [英] Extracting Data from JSON Using PHP

查看:99
本文介绍了从JSON使用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"]}]} 

我正在试图做的是提取的数据,如果PET含有猫或鱼或两者兼而有之。另一位用户提出了一个过滤器这样:

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

推荐答案

它应该是这样的:

foreach($JSONarray['MEMBERS'] as $p) {

    if (array_diff($p['PET'], $filter) != $p['PET']) {
        echo $p['NAME'].'</br>';
    }
}


  • 记住,总是使用引号当您试图访问一个关联数组的元素。不带引号,PHP会尝试跨preT它作为一个常量(在失败时抛出通知)。因此,而不是 $ A [指数] 不要 $一个['指数'] 。另请参阅为什么$ foo的[bar]错了?

    • 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?

      在您的code, $ P ['PET'] 将宠物名称的数组,而不是一个爱称。与 in_array测试()不会成功的,因为它会试图找到在 $过滤器整个阵列。在我的code示例,我使用 和array_diff() ,以找到两个阵列之间的差异,然后我把它比原来的数组。如果它们匹配,则 $过滤器宠物都没有发现。

      In your code, $p['PET'] will be an array of pet names, not one pet name. Testing with in_array() won't be successful, because it will try to find the whole array in $filter. In my code example, I used array_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.

      这篇关于从JSON使用PHP提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆