Skip to content
Advertisement

Filtering JSON data with php

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"
    }
  ]
}

for example

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

my php code is

$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.

Advertisement

Answer

$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();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement