using the below code for decoding json
$categories = json_decode($data);
$categories = $categories->data;
where i get this
{"categories":[{"id":1,"name":"Utilities","apps":897,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/uti.jpg"},{"id":2,"name":"Productivity","apps":477,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pro.jpg"},{"id":3,"name":"Music","apps":466,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/mus.jpg"},{"id":4,"name":"Travel","apps":289,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/tra.jpg"},{"id":5,"name":"Navigation","apps":297,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/nav.jpg"},{"id":6,"name":"Books","apps":271,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/boo.jpg"},{"id":7,"name":"Healthcare & Fitness","apps":250,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/hea.jpg"},{"id":8,"name":"Games","apps":5116,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/gam.jpg"},{"id":9,"name":"Social Networking","apps":272,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/soc.jpg"},{"id":10,"name":"Lifestyle","apps":434,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/lif.jpg"},{"id":11,"name":"Finance","apps":200,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/fin.jpg"},{"id":12,"name":"News","apps":128,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/new.jpg"},{"id":13,"name":"Photography","apps":481,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pho.jpg"},{"id":14,"name":"Entertainment","apps":1251,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ent.jpg"},{"id":15,"name":"Business","apps":221,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/bus.jpg"},{"id":16,"name":"Sports","apps":199,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/spo.jpg"},{"id":17,"name":"Education","apps":433,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/edu.jpg"},{"id":18,"name":"Medical","apps":262,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/med.jpg"},{"id":19,"name":"Weather","apps":64,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/wea.jpg"},{"id":20,"name":"Reference","apps":419,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ref.jpg"}]}
and i would like to convert to in an array like this
Array[0]
{
id => 1
name => Utilities
apps => 897
iconurl => http:\/\/static.apptrackr.org\/caticons\/uti.jpg
}
and so on
This looks like a JSON string. You can use json_decode() to convert it into a PHP variable, e.g.
$obj = json_decode($json);
print_r($obj->categories); // array of StdClass objects
You can access and iterate the categories array regularly
echo $obj->categories[0]->name; // Utilities
echo $obj->categories[1]->name; // Productivity
echo $obj->categories[2]->name; // Music
To convert the StdClass objects to arrays, you could do
$categories = array();
foreach (json_decode($json)->categories as $category) {
$categories[] = (array) $category;
}
print_r($categories);
You could also do it with a lambda function and array_map:
// Before PHP5.3
$categories = array_map(
create_function('$el', 'return (array) $el;'),
json_decode($json)->categories);
// After PHP5.3
$categories = array_map(
function($el) { return (array) $el; },
json_decode($json)->categories);
Erm, you can just set the 2nd parameter to convert JSON into an array instead of into an object:
$categories = json_decode($data, true);
take a look at get_object_vars
http://php.net/manual/en/function.get-object-vars.php
#Gordon seems correct - that looks like JSON. Assuming, though, that you're dealing with an "actual" PHP Object, then it will be iterable; simply run through it with a foreach and push each key/value pair into your destination array.
Related
Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion
I have converted an array in JSON. But the conversion puts arrays inside the JSON object.
My conversion is this:
{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}
Have you can beginning in key "0":{"make":"Mercedes-Benz"}, the interior of the JSON changes anI i can not submit it to an api.
I need my JSON object to be entirely like its beggining:
"title":"acastro","description":"teste acastro 4","category_id":29,"make":"Mercedes-Benz","model":"GLC220",...
and so on.
I tried with json_encode and JSON_FORCE_OBJECT but without luck.
Any solutions?
You can try below code but its not tested:
$json = '{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}}';
$newArr = array();
function recursiveArrayShiftToRoot($array, &$newArr=array()){
global $newArr ;
foreach($array as $index=>$eachMixVal){
if(is_array($eachMixVal)){
recursiveArrayShiftToRoot($eachMixVal);
}else{
$newArr[$index] = $eachMixVal;
}
}
}
recursiveArrayShiftToRoot(json_decode($json, true), $newArr);
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;
}
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);
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