用php过滤JSON数据 [英] Filtering JSON data with php

查看:70
本文介绍了用php过滤JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历此json文件并过滤掉我想拆分结果的不需要的元素,因此我有一个客户列表或一个供应商列表 json文件:

I am trying to iterate over this json file and filter out the unwanted elements I would like to split the result so I have have a list of Customers or a list of Suppliers json File:

{
  "$descriptor": "Test",
  "$resources": [
    {
      "$uuid": "281d393c-7c32-4640-aca2-c286f6467bb1",
      "$descriptor": "",
      "customerSupplierFlag": "Customer"
    },
    {
      "$uuid": "87a132a9-95d3-47fd-8667-77cca9c78436",
      "$descriptor": "",
      "customerSupplierFlag": "Customer"
    },
    {
      "$uuid": "8a75345c-73c7-4852-865c-f468c93c8306",
      "$descriptor": "",
      "customerSupplierFlag": "Supplier"
    },
    {
      "$uuid": "a2705e38-18d8-4669-a2fb-f18a87cd1cc6",
      "$descriptor": "",
      "customerSupplierFlag": "Supplier"
    }
  ]
}

例如

    {
      "$uuid": "281d393c-7c32-4640-aca2-c286f6467bb1",
      "$descriptor": "",
      "customerSupplierFlag": "Customer"
    },
    {
      "$uuid": "87a132a9-95d3-47fd-8667-77cca9c78436",
      "$descriptor": "",
      "customerSupplierFlag": "Customer"
    },

我的php代码是

$array = json_decode($result, true);


for ($i = 0; $i < count($array['$resources']); $i++){
    foreach ($array['$resources'][$i]['customerSupplierFlag'][Customer] as $item)
    {
        // do what you want
        echo $item['customerSupplierFlag' ]. '<br>';
        echo $item['$uuid'] . '<br>';
    }
}

几天来,我一直在为此苦苦挣扎,似乎正在翻阅同一篇文章,现在就得到任何建议,我们将不胜感激.

I have been struggling with this for a few days now an appear to be going over the same articles and getting now were any suggestions would be appreciated.

推荐答案

$data = file_get_contents('./your_json_data.txt');

$json = json_decode($data, 1);

$resources = $json['$resources'];

$suppliers = array();
$customers = array();

foreach ($resources as $rkey => $resource){

    if ($resource['customerSupplierFlag'] == 'Customer'){

        $customers[] = $resource;

    } else if ($resource['customerSupplierFlag'] == 'Supplier') {

        $suppliers[] = $resource;

    }

}

header('Content-Type: application/json');

echo json_encode($customers);
echo json_encode($suppliers);

die();

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

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