extract from json object thats converte to array php - php

I try to extract data from an json object.
I mannaged to convert the json object to an array but i can't extract the data i want
The array and var_dump can be found here http://pastebin.com/f1ujbSCq
if you look in the array at object->object->attributes-attribute
You see values in the object class.
for example i want the the value where the name in the onject class is descr or admin-c,tech-c.
But i can't figer out how to do that
THis is the php code i use to extract data from json object to an array:
$domeinnaam = "2.0.0.0.0.0.0.1.8.6.9.0.2.0.a.2.ip6.arpa";
$ripeinfo = haalripezone($domeinnaam);
var_dump($ripeinfo);
print_r($ripeinfo);
function haalripezone ($domeinnaam)
{
$link = "https://rest.db.ripe.net/ripe/domain/$domeinnaam.json";
$downloadlink = file_get_contents($link);
$result = json_decode($downloadlink);

You see values in the object class. for example i want the the value
where the name in the onject class is descr or admin-c,tech-c.
Since you have already decoded the JSON as an object, You could access your fields like this..
echo $yourObject->objects->attributes->attribute->name; //"prints" admin-c
You could alternatively loop through using a foreach construct..
<?php
$domeinnaam = "2.0.0.0.0.0.0.1.8.6.9.0.2.0.a.2.ip6.arpa";
$ripeinfo = haalripezone($domeinnaam);
echo "<pre>";
foreach($ripeinfo->objects->object[0]->attributes->attribute as $attr)
{
echo $attr->name."<br>";
}
function haalripezone ($domeinnaam)
{
$link = "https://rest.db.ripe.net/ripe/domain/$domeinnaam.json";
//$downloadlink = file_get_contents($link);
$downloadlink = '{"objects":{"object":[{"type":"domain","link":{"type":"locator","href":"http://rest.db.ripe.net/ripe/domain/2.0.0.0.0.0.0.1.8.6.9.0.2.0.a.2.ip6.arpa"},"source":{"grs-mirror":[],"id":"ripe"},"primary-key":{"attribute":[{"name":"domain","value":"2.0.0.0.0.0.0.1.8.6.9.0.2.0.a.2.ip6.arpa"}]},"attributes":{"attribute":[{"name":"domain","value":"2.0.0.0.0.0.0.1.8.6.9.0.2.0.a.2.ip6.arpa"},{"name":"descr","value":"Reverse delegation for Glue network ipv6 tunnel server"},{"name":"nserver","value":"ns3.hobby.nl"},{"name":"nserver","value":"ns2.hobby.nl"},{"name":"nserver","value":"ns1.hobby.nl"},{"link":{"type":"locator","href":"http://rest.db.ripe.net/ripe/role/HNET2-RIPE"},"name":"admin-c","value":"HNET2-RIPE","referenced-type":"role"},{"link":{"type":"locator","href":"http://rest.db.ripe.net/ripe/role/HNET2-RIPE"},"name":"tech-c","value":"HNET2-RIPE","referenced-type":"role"},{"link":{"type":"locator","href":"http://rest.db.ripe.net/ripe/role/HNET2-RIPE"},"name":"zone-c","value":"HNET2-RIPE","referenced-type":"role"},{"link":{"type":"locator","href":"http://rest.db.ripe.net/ripe/mntner/HOBBYNET-RIPE-MNT"},"name":"mnt-by","value":"HOBBYNET-RIPE-MNT","referenced-type":"mntner"},{"name":"source","value":"RIPE","comment":"Filtered"}]},"tags":{"tag":[]}}]},"terms-and-conditions":{"type":"locator","href":"http://www.ripe.net/db/support/db-terms-conditions.pdf"}}';
$result = json_decode($downloadlink);
return $result;
}
OUTPUT :
domain
descr
nserver
nserver
nserver
admin-c
tech-c
zone-c
mnt-by
source
Demo

try
$result = json_decode($downloadlink, true);
This way the decode will be totally put into an array, then accessing the data will be easier

Related

Decode php://input json

I have this text from file_get_contents('php://input'):
[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]
I need to get single element like email or event, but haven't been able to get json_decode and others to work.
$obj = json_decode(file_get_contents('php://input'));
How can I reference a single element in the json data?
You have an array, so, you need to get the first element:
$json = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($json);
echo $obj[0]->email; //output text#examlple.com
Here you go, here's a fully working answer:
<?php
$str = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($str);
echo $obj[0]->email;

How do i split and assign that data? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
How can i split that image or assign an array in PHP.
[{"ID":2,"no":123,"pname":"400","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]
I tried to split but it is a little weird.
I use this =>
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
// return $pieces[0];
$datas = array(
'ID' =>str_replace('"ID":','',$pieces[0]),
'poz_no'=>str_replace('"poz_no":','',$pieces[1]),
'poz_name'=>"asd",
'unit'=>str_replace('"unit":','',$pieces[3]),
'bid_count'=>str_replace('"bid_count":','',$pieces[4]),
'unit_price'=>str_replace('"unit_price":','',$pieces[5]),
'est_unit_price'=> str_replace('"est_unit_price":','',$pieces[6]),
'progress_count' =>str_replace('"progress_count":','',$pieces[7]),
'i_project'=>str_replace('"i_project":','',$pieces[8]),
'seq' =>str_replace('"seq":','',$pieces[9])
);
I did it myself but it seems weird:
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
$datas = array(
'ID' =>str_replace('"','',str_replace('"ID":','',$pieces[0])),
'poz_no'=>str_replace('"','',str_replace('"poz_no":','',$pieces[1])),
'poz_name'=>str_replace('"','',str_replace('"poz_name":','',$pieces[2])),
'unit'=>str_replace('"','',str_replace('"unit":','',$pieces[3])),
'bid_count'=>str_replace('"','',str_replace('"bid_count":','',$pieces[4])),
'unit_price'=>str_replace('"','',str_replace('"unit_price":','',$pieces[5])),
'est_unit_price'=>str_replace('"','',str_replace('"est_unit_price":','',$pieces[6])),
'progress_count' =>str_replace('"','',str_replace('"progress_count":','',$pieces[7])),
'i_project'=>str_replace('"','',str_replace('"i_project":','',$pieces[8])),
'seq' =>str_replace('"','',str_replace('"seq":','',$pieces[9]))
);
You can use json_decode for this.
If you have your string:
$json = '[{"ID":2,"poz_no":123,"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]';
You can simply do:
$datas = json_decode($json, true);
Now in $datas you have an array with all the fields from json.
As you can see in json you have an array of objects with only one element. If you want only that first element you can do after:
$datas = $datas[0]; //get first element of array.
Your are actually dealing with a JSON encoded Data here. So, you may need to first convert the JSON Data to Standard PHP Object. And then you can simply access your preferred values using normal PHP Object Access Notation. The commented Code below attempts to illustrate (however vaguely) the Idea.
THE GIVEN JSON DATA:
<?php
$jsonString = '[{
"ID":2,
"poz_no":123,
"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi",
"unit":"mt",
"bid_count":"4568",
"unit_price":"56",
"est_unit_price":"21.31",
"progress_count":"3841",
"i_project":117,
"seq":0
}]';
THE PROCEDURE:
<?php
// CONVERT THE JSON DATA TO NATIVE PHP OBJECT...
$arrJSONData = json_decode($jsonString);
// NOW, YOU COULD ACCESS THE PHP OBJECT BY DOING: $arrJSONData[0]
$objJson = $arrJSONData[0];
// IF YOU DID IT LIKE THIS; FROM THIS POINT YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
// HOWEVER, WHAT IF THE JSON DATA CONTAINS MORE THAN ONE ENTRY?
// THEN A LOOP WOULD BE NECESSARY...
// LOOP THROUGH THE RESULTING ARRAY OF OBJECTS AND GET YOUR DATA...
foreach($arrJSONData as $jsonData){
// AGAIN; YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
}

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Processing Multidimensional JSON Array with PHP

This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);

Categories