How to get values of a json array in php? - php

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?

$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo

You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

Related

Loop through JSON and store values to PHP arrays

I have a JSON with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?
$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.
<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));
You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));
You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode
Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}
After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.

Get JSON from URL by PHP

I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);

How to loop json and parse the value

This is my php code [EDITED]:
$redis_data = file_get_contents("http://example.org/data/data.txt");
That code returns the following json data:
{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302}
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302}
This is my code to looping parse the value:
$redis_data = file_get_contents("http://example.org/data/data.txt");
$redis_data = json_decode($redis_data, true);
foreach ($redis_data as $data) {
echo $data['Phone'];
echo "<br>";
}
But I got this errors:
Invalid argument supplied for foreach()
What am I doing wrong?
The data you trying to get is not well formatted json
[{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}]
This is the json syntax.
and you are getting data in following format.
{"ANumber":"08122378673","BNumber":"500046","StartTime":"08122014102113","EndTime":"08122014104126","TrunkA":"S1JK2SBD1S","TrunkB":"N7JK2GSM1B","Customer":"PT.BNI","time":1407921302}
{"ANumber":"081351607600","BNumber":"14000","StartTime":"08122014102406","EndTime":"08122014103738","TrunkA":"S1JK2SSB1S","TrunkB":"EPJK2MNR0","Customer":"Bank Mandiri (CC_IB_Jasnita)","time":1407921302}
You may need to reformat your data string
You're trying to loop JSON - not PHP. You need to run json_decode (docs) on the your $redis_data variable before attempting to loop it.
$redis_data = json_decode($redis_data, true);
You need to decode the json before you can loop through it.
$redis_data = json_decode(file_get_contents("http://example.com/tes_files/data.txt"), true);
foreach ($redis_data as $data) {
echo $data['phone'];
}
Here is solution
$redis_data = explode( chr(10), file_get_contents("http://example.com/tes_redis/data.txt"));
foreach ($redis_data as $data) {
var_dump(json_decode($data));
$data = json_decode($data);
echo $data->Phone;
echo $data->StartTime;
echo $data->Customer;
//echo $data->ANumber;
//echo $data->BNumber;
}
you need to export data first.
first you have to convert json to array using json_decode function it will give array and after that you can loop
`
$jsonString =
'[{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302},
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302},
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302} ]';
$array=json_decode($jsonString);
foreach ($arrayOfEmails as $data) {
echo $data->Phone."<br>";
}
`

loop json array and return values in php

I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync. I use PHP: 5.4.7
this is json var $json
{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}
when I try to get the values
$js=json_decode($json,true);
foreach ($js['formaspago'] as $row ) {
echo $row["Formapago"];
}
I get this error:
Invalid argument supplied for foreach
any help is appreciated
use json_decode
//array
$data = json_decode($json, true);
foreach($data["data"]["formaspago"] as $row) {
echo $row["Formapago"];
}
Thanks #JimL for the hint.
You're not passing a valid array to the foreach loop. However, even if you parse the json you've supplied, a foreach won't work because it's an object not an array.
$json = '{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}';
$obj = json_decode($json);
print $obj->info will return an empty string.
$obj->data is an object that has various properties some of which are empty arrays. Passing these into the foreach should work. i.e.
foreach($obj->data->clients as client) {
// Do something here
}
Further, $obj->data->formaspago has exactly one element in the array, which is an object. You can access this object with a foreach loop:
foreach($obj->data->formaspago as formaspago) {
print formaspago->idFormaPago; // Will print 7
print formaspago->FormaPago; // Will print "quwuw"
print formaspago->Dias; // Will print 1
print formaspago->Cuotas; // Will print 1
print formaspago->last_sync_date; // Will print nothing
}

Getting JSON data with PHP

Apologies if this has been asked a thousand times, but I can't find a good tutorial on how to do this correctly and searching on Stack is coming up trumps.
I have a JSON file which has data like this:
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
with about 50 entries in it. I'm trying to parse this data and store the values in variables.
So far I've tried:
$string = file_get_contents("jsonFile.json");
$json_array = json_decode($string,true);
foreach ($json_array as $key => $value){
$store = $key -> store;
$general_cat = $key -> general_cat;
$spec_cat = $key -> spec_cat;
if (!is_null($key -> mainImg_select)){
$cat = $key -> cat;
}
echo $headURL;
}
This is resulting in "Trying to get property of non object" errors. What am I doing wrong here?
The second argument of json_decode tells the function whether to return the data as an object, or an array.
Object access uses the -> symbol. To return an object from json_decode either use json_decode($jsonString) or json_decode($jsonString, false) (the second argument is false by default)
$jsonString = '{ "this_is_json" : "hello!" }';
$obj = json_decode($jsonString);
echo $obj->this_is_json // "hello!";
You can also access your json data as an array by setting the second argument to true
$jsonString = '{ "this_is_json" : "hello!" }';
$arr = json_decode($jsonString, true);
echo $arr['this_is_json'] // "hello!";
What can be a little more conceptually confusing, is that PHP json_decode can return either an array of objects (rather than just an object), or an associative array.
Consider the following json string. This string represents a "collection" (square brackets) of json data structures (curly braces).
[
{
"name": "One"
},
{
"name": "Two"
}
]
If we assign this json to the variable $string hopefully this will illustrate the difference
$asObjects = json_decode($string);
$asAssociativeArray = json_decode($string, true);
foreach ($asObjects as $obj) {
echo $obj->name;
}
foreach ($asAssociativeArray as $arr) {
echo $arr['name'];
}
It seems like you are requesting an associative array (by passing True as the second parameter to the json_decode function) but trying to use it as an object.
Try $json_array = json_decode($string,false); . That will return objects
Also, as #MatRt mentions, you need to use $value instead of $key to reference the objects
You need to retrieve values with array syntax:
$item['key']
as apposed to
$item->key

Categories