JSON to PHP array issue - php

I have tried to use PHP decode to parse my JSON string below into an array so I can extract the current and day for both channels from the file.
my json file owl_output.json looks like..
{"channels":{"0":[{"current":1288,"units":"w"},{"day":31278.57,"units":"wh"}],"1": [{"current":660,"units":"w"},{"day":9191.11,"units":"wh"}]}}
I'am only ever getting one result displayed, the php code I have managed to get working is below
<?php
$string = file_get_contents('owl_output.json');
$data = json_decode($string,true);
print_r($json);
foreach ($data['channels']['0'] as $data)
{
echo $data ['current'];
}
?>
This only display the current for channel 0. If I try to add additional fields it doesn't display
echo $data ['current']['day']; ( doesn't work )
Can someone advise how I can display current and day for both channels 0 & 1 ?
My aim is to display this in a html page at the end and to keep polling the json file?
The array it displays is below
Array
(
[channels] => Array
(
[0] => Array
(
[0] => Array
(
[current] => 1288
[units] => w
)
[1] => Array
(
[day] => 31278.57
[units] => wh
)
)
[1] => Array
(
[0] => Array
(
[current] => 660
[units] => w
)
[1] => Array
(
[day] => 9191.11
[units] => wh
)
)
)
)
Can anyone offer any assistance with this ?
Thanks

The variable $data is conflicting:
Used to store the data, and used in the foreach loop. Rename the $data variable in the foreach for example:
<?php
$string = file_get_contents('owl_output.json');
$data = json_decode($string,true);
print_r($json);
foreach ($data['channels'] as $channel)
{
echo $channel[0]['current'];
echo $channel[1]['day'];
}
?>
I did edit since there was an other error because there is not 'current' in every record.

Conflict on $data reference in loop and bad array indexes :
foreach ($data['channels'] as $channel)
{
echo $channel[0]['current'];
echo $channel[1]['day'];
}

foreach ($data['channels'] as $chanel)
{
echo $chanel[0]['current'];
echo $chanel[1]['day'];
}

Related

Get Data from JSON decode Using Pgp

So i have a function that checks for reference in my system which is like a pyramid, i want to display who you invited and who he or she invited too, im using this foreach loop to get all reference under a user id and save them in json. but im having problem listing or extrating the results using php.
here is my pup recursive function to find all children or an entered user.
<?php
include 'includes/connect.php';
$menu['Users'] =getChildren(2);
echo '<pre>'; print_r($menu); // check tree array
function getChildren($parent_id)
{
$db=new mysqli('localhost','root','P=3h?9)Do#R#w2NQ','tobo'); //db
$refs=$db->query("SELECT * FROM users WHERE ref=$parent_id");
$children = array();
$i = 0;
foreach ($refs as $key => $downline) {
$children[$i] = array();
$children[$i]['fname'] = $downline['fname'];
$children[$i]['downline'] =getChildren($downline['id']);
$i++;
}
return $children;
}
$myJson = json_encode($menu);
$newJson = json_decode($myJson, true); ?>
it works fine and i get the following result:
Array
(
[Users] => Array
(
[0] => Array
(
[fname] => Andrey
[downline] => Array
(
[0] => Array
(
[fname] => Alisa
[downline] => Array
(
[0] => Array
(
[fname] => Maxim
[downline] => Array
(
[0] => Array
(
[fname] => james
[downline] => Array
(
)
)
)
)
)
)
)
)
[1] => Array
(
[fname] => Satori
[downline] => Array
(
)
)
)
)
my question is how can i get this result in a list using php so i can display the to the user as a list.
i tried to decode but im new to json so its still not usable by me. i hope you will be patient with my question structure, thank u very much

How do I loop through using foreach for a json decoded array

Array
(
[id] => 7.8803211967429E+17
[title] => Example T-Shirt
[body_html] =>
[variants] => Array
(
[0] => Array
(
[id] => 6.4266704147271E+17
)
[1] => Array
(
[id] => 7.576504846442E+17
[product_id] => 7.8803211967429E+17
)
)
[options] => Array
(
[0] => Array
(
)
)
)
I need to get IDs from each main array. I get this array from decoding json using:
<?php
set_time_limit(0);
$json = file_get_contents('imarasoft.net/imarasoft/abd/WebHook/response.txt');
$arrays = json_decode($json, true);
print_r($arrays);
foreach ($arrays as $array) {
echo $array["id"];
}
How can I print ID using foreach?
i HAVE EDITED THE QUESTION AND HAVE GIVEN THE FULL ARRAY FORMAT
If you are getting more number of elements in the array then you can use below snippets. This foreach loop go through all the arrays and gives value of each array's key. Here you can any value like title, id, vendor, product_type etc...
If you want access id inside variants then use below code.
$json = file_get_contents('http://imarasoft.net/imarasoft/abd/WebHook/response.txt');
$arrays = json_decode($json, true);
foreach ($arrays["variants"] as $array) {
echo $array["id"];
}
And if you only want to access root id then you just need to do only one line snippet.
echo $arrays["id"];

limit JSON results using php

I am facing with a problem that my json results cannot be limited..
My json result contains a large number of data, I just want to limit the results so that i can print some of the data in my view page. How can i do that?
Here is my code
$post1 = file_get_contents("........");
$products = CJSON::decode($post1, true);
for($i=1;$i<=5;$i++)
{
echo "<pre>";print_r($products);
}
This code prints all the contents. Please help me with this ,waiting for the response.
Output of $products.
Array
(
[0] => Array
(
[id] => 4380
[title] => 13 Thirteen Patch
[barcode] => PAT-2288
[qty] => 17
[url] => http://www.heygidday.biz/13-thirteen-motorcycle-club-mc-fun-embroidered-quality-new-biker-patch-pat-2288.html
[retail_price] => 4.99
[category] => Array
(
[id] => 1
[name] => SMALL PATCHES
)
[bin] => Array
(
[id] => 1
[name] => A1
)
[images] => Array
(
[0] => Array
(
[small] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/pat-2288-013678719880.jpg&w=30
[middle] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/pat-2288-013678719880.jpg&w=100
[source] => http://www.heygidday.biz/portal/files/products/pat-2288-013678719880.jpg
)
)
)
....................
[6619] => Array
(
[id] => 12921
[title] => Special Police- BLACK Leather Key Fob
[barcode] => FOB-0435
[qty] => 1
[url] =>
[retail_price] => 8.99
[category] => Array
(
[id] => 54
[name] => KEY FOBS
)
[bin] => Array
(
[id] => 382
[name] => F10-21
)
[images] => Array
(
)
)
)
Hope this is useful.
Simpler answer
Just use array_slice to take out the number of elements you want:
echo "<pre>";
print_r(array_slice($products,0,5));
echo "</pre>";
The pitfalls I pointed to in Ben's answer are still relevant.
Original answer
print_r($products) will print the entire array each time through the loop. To limit the number of elements printed to 5, do:
Replace your for loop with:
for($i=0;$i<(min(5,count($products)));$i++):
echo "<pre>";
print_r(each($products)['value']);
echo "</pre>";
endfor;
Two pitfalls to watch out for in Ben Shoval's answer:
You should add a safeguard against going beyond the end of the array. If your $products has just 3 items, and you loop 5 times, you will run into an error. That's why I have the max $i set to min(5,count($products)
If you use the index $i to refer to each element, your code will fail if $products is an associative array (with named keys instead of indices 0,1...). This is why I use each($products)['value'] to access the value when I don't know the key
Change:
echo "<pre>";print_r($products);
To:
echo "<pre>";print_r($products[$i]);
You did wrong code, you have printed json decode resposne 5 times.
You should check what keys in the json decoded response and then try to get specific data you want.
For example:
if you want first 5 elements of response then:
$c = 0;
foreach($products as $p){
print_r($p);
$c++;
if($c == 5){
break;
}
}
I got the answer.This is how i done ........
Controller
$data = file_get_contents("............",true);
$result = json_decode($data);
$prod = array();
$i =0;
foreach($result as $rest){
$product = json_decode(json_encode($rest),true);
foreach($product as $prods){
$prod[] = array_merge($prods);
}
$new_array = array_slice($prod, 0, 5);
$this->render('index',array('model'=>$model,'products'=>$new_array));
}
View page
<?php
foreach($product as $prod):
?>
<li style="width: 200px;">
<?php
$img = array();
foreach($prod['images'] as $img):
//echo $img['middle'];
echo CHtml::image($img['source'],'',array('alt'=>'Image 3'));
// $i++;
endforeach;
// echo CHtml::link($img,'detail');
?>
<div class="list-holder">
<h4><?php echo $prod['title'];?></h4>
<div class="rating"> <span>$<?php echo $prod['retail_price'];?></span></div>
</div>
</li>
<?php
endforeach;
?>
This code displayed first 5 products in my view..
Thanks for all the answers provided and time...

How can I put JSON to MySQL with PHP loop?

I have JSON like this (from nested sorting)
[
{"id":13},{"id":14},
{"id":15,
"children":[
{"id":16},{"id":17},{"id":18}
]
},
{"id":19},{"id":20},
{"id":21,
"children":[
{"id":22}
]
}
]
how I PHP loop to put this JSON in MySQL
Thank you.
As with any valid JSON format string, you can use PHP's built-in json_decode to convert it into a parsable object and then loop through those parameters. In this case, from the JSON string you've given (which seems to be an array)
$array = json_decode($string);
foreach ($array as $val) {
//The object $val will be:
"id":13
}
If it's nested, you would do another foreach loop and detect for the property that needs to be looped. For example you could do this in a variety of ways (check for the "children" property, loop through the $val properties and check if it is an array, if it is then loop through that). Inside this foreach loop iteration, you can insert it, or do execute whatever statement you need to get it inside MySQL
Your question is pretty vague on the format and way you want it inserted. I'd suggest showing some code you've tried so other people can help you and know what direction you're going in. (that's probably the reason for the downvote, not mine by the way)
Looping through all the properties of object php
just put your valid json inside json_decode and assign it to a php array as below
//$php_arr = json_decode('YOUR_JSON');
$php_arr = json_decode('[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]');
/*comment the following 3 lines when done*/
echo "<pre>";
print_r($php_arr);
echo "</pre>";
/*comment the above 3 lines when done*/
output
Array
(
[0] => stdClass Object
(
[id] => 13
)
[1] => stdClass Object
(
[id] => 14
)
[2] => stdClass Object
(
[id] => 15
[children] => Array
(
[0] => stdClass Object
(
[id] => 16
)
[1] => stdClass Object
(
[id] => 17
)
[2] => stdClass Object
(
[id] => 18
)
)
)
[3] => stdClass Object
(
[id] => 19
)
[4] => stdClass Object
(
[id] => 20
)
[5] => stdClass Object
(
[id] => 21
[children] => Array
(
[0] => stdClass Object
(
[id] => 22
)
)
)
)
Now as you have PHP array do what ever you want like
foreach($php_arr as $arr){
if(!isset($arr['children'])){
$q = "insert into tbl(id) values('".$arr['id']."')";
}else{
//your logic
}
}
You need to use json_decode function to decode JSON data. Then use foreach loop to manipulate data.
Try example
$str = '
[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]
';
$json = json_decode($str);
//var_dump($json);
foreach ($json as $item)
{
//The object $val will be:
echo $item->id."<br />";
//You INSERT query is here
//echo "INSERT INTO table (field) VALUE ($item->id)";
$query = mysqli_query($conn, "INSERT INTO table (field) VALUE ($val->id)");
}

Retrieving values from multi level array

Hi would love some help on how to perform this. Cause so far what I'm doing now is failing.
this is the sample output of json turned to array.
Array
(
[0] => Array
(
[0] => Array
(
[value] => lit-PR-00-Preparing-Precise-Polymer-Solutions.html
)
)
[1] => Array
(
[0] => Array
(
[value] => 90Plus
)
)
[2] => Array
(
[0] => Array
(
[value] => Particle Size Analyzer
)
)
)
So far this is what I got so far and It's still not outputting the value I need. Would appreciate some help on what I'm doing wrong thanks.
$decode = json_decode($row['elements'], true);
echo '<pre>';
//print_r($decode);
print_r(array_values($decode));
echo '</pre>';
echo ($value['0'][1][value]);
$decode = json_decode($row['elements'], true);
// iterate through array
foreach($decode as $array_row) {
echo $array_row[0]['value'];
}
// display specific row #2
echo $decode[2][0]['value'];
PHP Arrays

Categories