please help to parse json - php

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

Related

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

Remove the last charater from string which is generated in loop

Believe me, I have tried everything that is there in stack overflow!
So, I got this JSON -
$j={
"itempicture": [
{
"status": "3"
},
{
"ItemCode": "001",
"ItemImage": "image1",
"ItemCategory": "shirt",
"ShowOnPOS": "Yes",
"LastModifiedOn": "2018-06-02 11:53:57"
},
{
"ItemCode": "002",
"ItemImage": "image2",
"ItemCategory": "shirt",
"ShowOnPOS": "Yes",
"LastModifiedOn": "2018-06-02 11:53:57"
}
]
}
and i am accessing it like this -
$jo = json_decode($j);
for($i = 1; $i < count($jo->itempicture); $i++) {
foreach($jo->itempicture[$i] as $prop=>$val) {
echo $val.",";
}
echo '<br>';
}
and I'm getting this output -
001,image1,shirt,Yes,2018-06-02 11:53:57,
002,image2,shirt,Yes,2018-06-02 11:53:57,
The main prob with this output is the "," at the last.
I am unable to remove it!
Tried everything -
This -
Remove the last character from string
with substr, rtrim, implode...
EVERYTHING!
It's not working!
A version using implode() which means that you have to convert from JSON into arrays (the default is to convert to objects, so add true as second paramter to json_decode()).
$j='{"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}
]
}';
$jo=json_decode($j, true);
array_shift($jo['itempicture']);
$edata = '';
foreach ( $jo['itempicture'] as $item) {
$edata .= implode(",", $item).'<br/>';
}
echo "<pre>";
print_r($edata);
echo "</pre>";
Prints out...
<pre>001,image1,shirt,Yes,2018-06-02 11:53:57<br/>
002,image2,shirt,Yes,2018-06-02 11:53:57<br/></pre>
Here is the solution
$j='{"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}
]
}';
$jo=json_decode($j);
$edata = '';
for($i=1;$i<count($jo->itempicture);$i++){
$data = '';
foreach($jo->itempicture[$i] as $prop=>$val){
$data .= $val.",";
}
$edata .= rtrim($data, ",");
$edata .='<br/>';
}
echo "<pre>";
print_r($edata);
echo "</pre>";
You could do something like this
$jo=json_decode($j);
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
if ($value === end($jo->itempicture[$i])) {
echo $val;
}
else {
echo $val.",";
}
}
echo '<br>';
}
That would prevent from writing the last ',' by comparing if your current iteration is the end of the loop
If you know that the last element would always be LastModifiedOn
$jo=json_decode($j);
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
if($prop == "LastModifiedOn")
echo $val;
else
echo $val.",";
}
echo '<br>';
}

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['*'];

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.
$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']);
}
}

json parsing with php foreach

I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}

Categories