Echo statement printing more values than expected - php

I make call to api and in the response I receive JSON in which I access the array data like so. Problem is the JSON returns 50+ objects but I only want to echo 10 of them. In the URL that I am calling I was able to add a parameter to limit the JSON response to 10 and verified that only 10 are being returned. Problem is my echo statement still prints ALL 50+ of them.
1) How is it possible that I can echo 50+ when my JSON only returns 10?
2) Is there a For Loop that I can include below that can achieve echoing only 10?
<?php
$OfficeChartData = file_get_contents("http://api.xxxx...");
if (!empty($OfficeChartData)) {
$OfficeCharts = json_decode($OfficeChartData, true);
foreach ($OfficeCharts['value'] as $data) {
echo "<p>" . $data['Position']['Title'] . "</p>";
}
}
?>

Do something like:
<?php
$OfficeChartData = file_get_contents("http://api.xxxx...");
if (!empty($OfficeChartData)) {
$OfficeCharts = json_decode($OfficeChartData, true);
$cnt = 0;
foreach ($OfficeCharts['value'] as $data) {
if($cnt==10)break;
echo "<p>" . $data['Position']['Title'] . "</p>";
$cnt++;
}
}
?>

Related

Trying to add totals for each employee with data that is stored in array in PHP

So I am trying to write a script where I have obtained data that has employee names and the amounts they are paid from a database. The information was retrieved in JSON format, which I think I decoded correctly and put into an associative array. The problem I am running into is figuring out how to loop through the array to obtain the total paid for each employee.
Here is my code so far starting at the section where I decoded the JSON file.
//decode JSON file
$payout_array = json_decode($info, true);
echo '<pre>' . print_r($payout_array, true) . '</pre>';
/*foreach($payout_array as $key=>$value)
{
if($key['Name'] == "Jane")
{
$jane_payout = array_sum($value['Amount']);
}
if($name == "Mark")
{
$mark_payout = sum($amount);
}
}*/
/*foreach ($payout_array as $key => $sub_array) {
foreach ($sub_array as $sub_key => $value) {
if($value['Name'] == "Jane")
{
$jane_payout = array_sum($value['Amount']);
}
if($value == "Mark")
{
$mark_payout =+ sum($value['Amount']);
}
}
}*/
//Proccess data to calculate the amount paid to each employee
/*$mark_payout = array_sum($payout_array->Amount);*/
echo "Jane $".number_format($jane_payout, 2);
echo "<br>";
echo "Mark $".number_format($mark_payout, 2);
?>
The result I am currently seeing in the browser is
first section of array
second section of array
errors and total
On picture three you can see Jane and Mark show a total for $0.00. My goal is to have the $0.00 actually display the total that was paid to each employee from all the array entries. Once I am able to do that I will be encoding that new information into a JSON file and posting it to a client server. The end result that the client needs to see is the name of the employee and the total amount they have been paid.
I have tried various foreach loops and even left some commented out in the code but can't get it to access the elements correctly to perform the calculations. I am new to this and have very little experience with PHP so any help is very much appreciated!
Untested but this is generally what you're looking for.
<?php
$payout_array = json_decode($info, true);
echo '<pre>' . print_r($payout_array, true) . '</pre><br/><br/><br/><br/>';
foreach($payout_array['records'] as $key => $value)
{
if (!array_key_exists('fields', $value)) {
print 'Bad input data detected' . PHP_EOL;
}
$name = $value['fields']['Name'] ?? 'no name given';
$payout_array[] = [
'name' => $name,
'total_payout' => $total = $value['fields']['Amount'] ?? '0'
];
print $value['Name'] . ' $' . number_format($total, 2) . '<br/>';
}

I need a foreach (json) for params

I have this json file: and I would like to get all the title so my code is: var_dump($json['results'][0]['title']); but it getting just one title, I know I need to do a foreach but I don't know how :( so if you could help me that will be great ! Thanks
Your data is coming back as an array with item's inside of it. This mean's you'll need to loop through this JSON and print each item;
foreach($json['results'] as $movie) {
echo $movie['title'] . "<br />";
}
You will want to loop through all of the JSON results objects and echo or store the 'title' value;
foreach ($json['results'] as $object) {
//Option 1
echo $object['title'];
//Option 2
array_push($titles, $object['title'];
}
Assuming that the variable $json contains your data, I see two equivalent options in order to iterate trough the array
Using for
for($index = 0; $index < count($json['results']); $index++) {
echo $json['results'][$index]['title'] . "\n";
}
Using foreach
foreach($json['results'] as $movie) {
echo $movie['title'] . "\n";
}

creating one loop for parsing json data

So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.

PHP: Pulling JSON data out of database and displaying it

I'm using a php library from https://sourceforge.net/p/wowarmoryapi/home/Home/. It pulls json data from battle.net and stores it in my database for cache reasons.
code to get json from db (I'm not sure if it's still considered json at this point):
$data = $con->query('SELECT Data FROM wa_guilds');
I use the following code to see the data:
foreach($data as $row) {
echo "<span style='color:#ff0099'>";
var_dump($row);
echo "</span>"; }
which looks like this minus the errors, that's from another code:
I've tried various methods, mostly from this site to show my data in a way that's easy to read but I always get error.
This is definitely an object. if (is_object($data)) { echo "yay!"; } <--this works
Once I use $decodedjson = json_decode($data); it's no longer an object and I can't seem to print the results to see what it looks like. var_dump($decodedjson) returns NULL
Finally, when I use the following code:
foreach ($data as $da){
echo $da['Data']['character']['name']; }
returns Warning: Illegal string offset 'character'
and:
foreach ($data as $da){
echo $da['character']['name']; }
returns Notice: Undefined index: character
I don't understand what I'd doing wrong, or right. Do I need to somehow turn $data into a string?
NEW CODE
$sth = $con->query('SELECT Data FROM wa_guilds');
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
foreach($row as $r) {
$myData = json_decode($r, true);
echo "<span style='color:#ff0099'>";
var_dump($myData['Data']);
echo "</span>"; } }
NEW ERROR
NULL NULL
From the warning I'm guessing you're using PDO. If $con is your PDO instance representing a connection to a database, try the following:
$sth = $con->prepare('SELECT Data FROM wa_guilds');
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row) {
$myData = json_decode($row['Data'], true);
echo "<span style='color:#ff0099'>";
// $myData should now be a PHP array which you can access easily
print_r($myData);
echo "</span>";
}
You will need to convert the json string first, I'm not sure how many rows you are expecting from the DB but if it's only one you don't need the loop:
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$decoded = json_decode($data['Data'], true);
echo "<span style='color:#ff0099'>";
var_dump($decoded);
echo "</span>";
if you need a loop it should work like this:
foreach($data as $d)
{
$decoded = json_decode($d['Data'], true);
echo "<span style='color:#ff0099'>";
var_dump($decoded);
echo "</span>";
}

Looping code using PHP

I am currently using YouTube's API JSON-C response to pull data from a playlist and display the content in a list. I am doing this using PHP, however because YouTube restricts the maximum number of videos called, I have a hit a stumbling block. The maximum I can request is 50 whereas I have over 200 videos which I need to put in a list and I want to be able to do this dynamically.
I understand that I will have to loop the response, which is what I have done but is there a way it can be dynamically done?
If you could help me that would be great, my code is:
$count = 0;
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
if($count == 50) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=50&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
if($count == 100) {
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=100&max-results=50&v=2&alt=jsonc";
$data = file_get_contents($query);
if($data){
$data = json_decode($data);
foreach($data->data->items as $item) {
$count++;
echo $count." ".$item->id;
echo " - ";
echo $item->title;
echo "<br />";
}
}
}
}
and so on...
If you could help me out, or at least point me in the right direction that would be great, thanks.
One way is to loop over requests, and then over each item in the request. Like this:
$count = 1;
do {
$data = ...; // get 50 results starting at $count
foreach ($data->items as $item) {
echo "$count {$item->id} - {$item->title}<br />\n";
$count++;
}
} while (count($data->items) == 50);
Note that start-index is 1-based, so you have to query for 1, 51, 101 etc.
(This is actually quite similar to reading a file through a buffer, except with a file you've reached the end if the read gives you 0 bytes, while here you've reached the end if you get less than the amount you asked for.)
What I would do is first call the 4 pages, and then combine the results into 1 single array, then iterate over the data.
$offsets = array(0,50,100,150);
$data = array();
foreach($offsets as $offset)
{
$query = "http://gdata.youtube.com/feeds/api/videos?q=USERNAME&start-index=" . $offset . "&max-results=50&v=2&alt=jsonc";
$set = file_get_contents($query);
if(!emprty($set ))
{
$data = array_merge($data,json_decode($set));
}
}
//use $data here

Categories