Filtering JSON data with php - 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.

$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();

$array = json_decode($json, true);
$flag = "Supplier";
$resources = array_filter($array, function ($var) use ($flag) {
return ($var['customerSupplierFlag'] == $flag);
});
print_r($resources);

$json_a = json_decode($string, true);
foreach($json_a as $jsonDataKey => $jsonDataValue){
foreach($jsonDataValue as $jsonArrayKey => $jsonArrayValue){
print_r($jsonArrayValue['id']);
print_r($jsonArrayValue['name']);
}
}

Related

Can't Insert JSON Data into MySQL

I can't get the data in json format and insert it into mysql database.
I have this JSON format in employee_data.json
{
"MessageCode":"00",
"Message":[
{
"name":"Michael Bruce",
"gender":"Male",
"designation":"System Architect"
},
{
"name":"Jennifer Winters",
"gender":"Female",
"designation":"Senior Programmer"
}
]
}
Here is my PHP code
<?php
$connect = ysqli_connect("localhost", "root", "", "test");
$query = '';
$table_data = '';
$filename = "employee_data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$query .= "INSERT INTO tbl_employee(name, gender, designation)
VALUES ('".$row["name"]."',
'".$row["gender"]."',
'".$row["designation"]."'); ";
}
?>
How to $data return only
[
{
"name":"Michael Bruce",
"gender":"Male",
"designation":"System Architect"
},
{
"name":"Jennifer Winters",
"gender":"Female",
"designation":"Senior Programmer"
}
]
you need to first get the correct objects before going through the foreach
$array = json_decode($data, true);
$array = $array['message'];
foreach($array as $row) {}
or instead
foreach($array['message'] as $row) {}

Creating Multiple JSON Object Elements Programmatically using PHP

I need to create a JSON object, in PHP, with the following form
{
"Routes": [{
"route_ID": "49",
"geom": [{
"lat": "-30.63607",
"lng": "147.499935"
}, {
"lat": "-30.63631",
"lng": "147.499868"
}]
},
{
"route_ID": "50",
"geom": [{
"lat": "-30.63607",
"lng": "147.499935"
}, {
"lat": "-30.63631",
"lng": "147.499868"
}]
}
]
}
The problem with my code is that I can't seem to find a way of concatenating the JSON elements from the $jsonString, The code as it is just produces "route_ID": "50".
(Yes I agree there are a great many questions on stackoverflow on this question, but they just about all refer to single elements derived from a static array). By the way, I am given the $jsonString and need to preprocess it in the code below.
$jsonString = "[{\"route_ID\":\"49\",\"geom\":\"<LineString><coordinates>147.499935,-30.63607 <\\/coordinates><\\/LineString>\"},{\"route_ID\":\"50\",\"geom\":\"<LineString><coordinates>147.499935,-30.63607<\\/coordinates><\\/LineString>\"}]";
/* PHP Code */
$jsonArray = json_decode($jsonString, true);
$json = new stdClass();
$json_Routes = new stdClass();
$route_geom_Array = array();
foreach ($jsonArray as $record) {
print_r($record);
$geomString = $record["geom"];
$geomString = str_replace('<LineString><coordinates>', ' ', $geomString);
$geomString = str_replace('</coordinates></LineString>', ' ', $geomString);
$geomString = trim($geomString);
$route_geom_Array = explode(' ', $geomString);
for ($i = 0; $i < sizeof($route_geom_Array); $i++) {
$var = explode(',', $route_geom_Array[$i]);
$route_geom[] = array('lat' => $var[1], 'lng' => $var[0]); // lat long
}
$json->route_ID = $record["route_ID"]; //<- Problem area
$json->geom = $route_geom; //<- Problem area
}
$json_Routes->Routes = $json;
$jsonArray = json_encode($json_Routes);
echo $jsonArray;
exit ();`
Can someone give me a clue on how do this.
Thanks
You need to make $json_Routes->Routes an array and push the $json structures within the foreach block, e.g.:
$json_Routes->Routes = [];
foreach ($jsonArray as $record) {
// Existing code ...
$json_Routes->Routes[] = $json;
}
You need to push objects to array, here solution :
$jsonArray = json_decode($jsonString, true);
$json_Routes = new stdClass();
$route_Array = [];
$route_geom_Array = [];
$route_ID_Array = [];
$items = [];
$index = 0;
foreach ($jsonArray as $record) {
//print_r($record);
$geomString = $record["geom"];
$geomString = str_replace('<LineString><coordinates>', ' ', $geomString);
$geomString = str_replace('</coordinates></LineString>', ' ', $geomString);
$geomString = trim($geomString);
$route_geom_Array = explode(' ', $geomString);
for ($i = 0; $i < sizeof($route_geom_Array); $i++) {
$var = explode(',', $route_geom_Array[$i]);
$route_geom[] = array('lat' => $var[1], 'lng' => $var[0]); // lat long
}
$json = new stdClass();
$json->route_ID = $record["route_ID"]; //<- Problem area
$json->geom = $route_geom; //<- Problem area
array_push($route_Array,$json);
}
$json_Routes->Routes = $route_Array;
$result = json_encode($json_Routes);
echo $result;
exit();

please help to parse json

JSON:
{
"hashrate": 551125275,
"miners": {
"0x0916c53bc9c5a934f9b3dc1b01abd56241569977": {
"lastBeat": 1538180874,
"hr": 139778683,
"offline": false
},
"0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6": {
"lastBeat": 1538180856,
"hr": 22072348,
"offline": false
}
},
"minersTotal": 2,
"now": 1538180878485
}
I want to get like this:
Account1:0x0916c53bc9c5a934f9b3dc1b01abd56241569977
Account2:0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6
$json = ' {
"hashrate": 551125275,
"miners": {
"0x0916c53bc9c5a934f9b3dc1b01abd56241569977": {
"lastBeat": 1538180874,
"hr": 139778683,
"offline": false
},
"0x3382e1265913d1f8161ead5422b7ca1e7cd80fc6": {
"lastBeat": 1538180856,
"hr": 22072348,
"offline": false
}
},
"minersTotal": 2,
"now": 1538180878485
}';
$data = json_decode($json);
$i = 1;
foreach ($data->miners as $key => $value) {
echo 'Account' . $i++ . ':' . $key . PHP_EOL;
}
The easiest way to work with JSON in PHP is using the JSON extension. See http://php.net/manual/en/book.json.php
So you can convert a JSON string to stdClass and vice-versa.
Like this:
$json_object = json_decode($json_string);
var_dump($json_object->miners);

json decode array PHP

I'm trying to decode a json string, i want to get just langlinks value,
my json string is:
{
"batchcomplete": "",
"query": {
"pages": {
"105219": {
"pageid": 105219,
"ns": 0,
"title": "Cancer",
"langlinks": [
{
"lang": "ar",
"*": "\u0633\u0631\u0637\u0627\u0646"
}
]
}
}
}
}
I tried this code:
$results = json_decode($api_response, true);
$list = array();
foreach ($results['query']['pages'] as $k => $v)
{
var_dump($v);
foreach($v as $key => $val)
{
array_push($list, $val);
}
}
return $list;
But it does not accede to the value that I want, when i add
var_dump(array_key_exists('langlinks', $v));
it gives me false :/
I just tested this and this seems to return true
$source = file_get_contents('https://en.wikipedia.org/w/api.php?action=query&titles=Cancer&prop=langlinks&lllang=ar&format=json');
$results = json_decode($source, true);
foreach ($results['query']['pages'] as $k => $v)
{
var_dump(array_key_exists('langlinks', $v));die();
}
If you are still having trouble, maybe you can post more code?
$list = array();
$src = json_decode($api_response, true);
foreach ($src['query']['pages'] as $key => $langData) {
foreach ($langData['langlinks'] as $k => $ld);
// var_dump($ld['*']);
}
return $ld['*'];

Foreach getting value null, why?

I am trying to get access to some data in PHP. If I print my docuements as a JSON object I get the document like so:
print_r($url);
[
{
"channel": "hello.com",
"partone": {
"click": 30580,
"load": 2156552
},
"parttwo": {
"click": 3274,
"load": 402327
},
"partthree": {
"click": 406467,
"load": 903869
}
}
]
So my main idea is to get the "click" of "parttwo" but I am getting null. This is my PHP code where I am making the mistake:
foreach ($url[0]['parttwo'] as $obj) {
$doc = array();
$doc['click'] = $obj['click'];
$param []= $doc;
}
Fo that data, simply:
$array = json_decode($url, true);
$param = $array[0]['part2']['click'];
If you really need to loop then:
foreach($array as $value) {
$param[] = $value['part2']['click'];
}

Categories