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

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

Related

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?

PHP reading json data

I'm new to PHP and web programming at all.I am trying to read some json data from steam API.
Data: http://pastebin.com/hVWyLrfZ
I managed to get to single objects(I believe?).
This is my code:
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
I want data to be in array like this:
id => name
I mean, array keys should be ids and values should be hero names.
Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?
You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(No need to do any reset calls; that's a weird way to get the first element of an array)
Note, for this to work, you must apply the tip by #RamRaider
$data = json_decode($JSON, true);
in order for json_decode to return arrays, not StdClass.

store array in the database

I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.

extract from json object thats converte to array 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

How do I remove an Attribute from a JSON String utilizing PHP

I have a JSON result in PHP that looks like the following:
[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]
I want to eliminate the Attributes (which contains Type and URL) so that the JSON result is flattened. So I'd like it to look more like:
[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]
What is the best way in PHP to eliminate every instance of attributes?
//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);
Using json_decode(), array_map() and json_encode() should be easy enough:
function strip_arguments( $item){
$new_result = array(
'Id' => $item['Id'],
'Name' => $item['Name'],
)
return $new_result;
}
$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);
You of course may use unset() inside strip_arguments (instead of creating new array) but this will make sure any "new attribute" won't make it trough.
You can use return array(...) instead of declaring variable and chain operations to: json_encode(array_map( 'strip_arguments', json_decode( $input))); too :)
Using PHP's JSON's tools you can convert the JSON string into an array, from here use a simple foreach statement and REGEX to delete array entries.
Once this is done simply convert back into a JSON string using PHP functions and do with it as you please :-)
The functions I am thinking off are - json_decode, json_encode.
Thanks
Andrew

Categories