Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering JSON data with php

Tags:

json

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.

like image 465
Artful_dodger Avatar asked Dec 05 '22 20:12

Artful_dodger


2 Answers

$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();
like image 88
myte Avatar answered Dec 20 '22 18:12

myte


$array = json_decode($json, true);
$flag = "Supplier";
$resources = array_filter($array, function ($var) use ($flag) {
    return ($var['customerSupplierFlag'] == $flag);
});
print_r($resources);
like image 41
jai3232 Avatar answered Dec 20 '22 17:12

jai3232