I would like to know how to count records within records in json.
if you look here you can see an example of the text i have.
http://russellhopedesign.com/facebook/toplikedstatus/data.js
now. i want to see which record has the most "likes"
Would i have to do some sort of For Each and then count?
edit: Re-editied per ongoing conversation with the OP.
I would do a loop to start with, to loop over all the data. have a variable to store the one you want to save, too. then for each index, do a foor each loop, checking for the property and seeing if it's equal to "likes". Each time you find one that has a likes property, get the length and save it
$json = json_decode(file_get_contents('https://graph.facebook.com/100002367437090/statuses?limit=100000000&access_token=145634995501895|c19bad6810f80442a09516c5.0-100002367437090|wcIUgp977G3_nSiJTCF3mY_PMis'), true);
$data = $json['data'];
$mostLiked = null;
$saved = false;
for($i = 0; $i < count($data); $i++){
foreach($data[$i] as $key => $value){
//echo "property is => " . $key . '<br>';
if($key == "likes"){
//echo "********* a like is here";
//echo '<br><hr>';
//echo 'No. of likes => ' . count($data[$i]['likes']['data']) . '<br>';
if(!$saved){
//echo "*** nothing saved yet, save what we've just found <br>";
$mostLiked = $data[$i];
$saved = true;
}else if($saved && (count($data[$i]['likes']['data']) > count($mostLiked['likes']['data']))){
//echo "*** this one is bigger than what was saved before <br>";
$mostLiked = $data[$i];
};
};
};
};
//var_dump($mostLiked);
echo 'This post has the most likes with => ' . count($mostLiked['likes']['data']);
Related
My objective is to create a multidimensional associative array with friends and their dreams (user input) in it. I think (hope) that I can am close to finishing it, but I get an unwanted result when echoing the final step:
I am trying to echo a sentence including the name of a 'friend' on line 22. Instead of a name inputted by the user, I get 'Array' as a result. E.g.: Array has this as their dream: Climbing Mount Everest
Does anyone know how I get the name of the friend here?
A line/string should be echoed for every separate dream that was filled in. And I included the print function for my clarity, will delete later. Thanks!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
try this after you assembled $array:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}
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/>';
}
Hey i have five json from all getting information now i encountered with problem like this -> from five different json i need to get latest videoId who newer shows first and all it need put to one function foreach for my too hard i try it do about 5hours and stay in same step
Json 1 json 2
All code need from this two json get latest(newest) videoId in one foreach echo
<?php
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$i = 0;
foreach($videoList1->items as $item){
if(isset($item->id->videoId)) {
echo $item->id->videoId;
if ( ++$i > 3) {
break;
}
}
}
Tray this:
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList = array_merge($videoList1["items"],$videoList2["items"]);
/// sort lastet first
foreach ($videoList as $key => $part) {
$sort[$key] = strtotime($part['snippet']['publishedAt']);
}
array_multisort($sort, SORT_DESC, $videoList);
foreach ($videoList as $video) {
if(isset($video["id"]["videoId"])) {
echo 'publishedAt: '. $video['snippet']['publishedAt'] . ' VideoID: ' . $video["id"]["videoId"] . "\n </br>";
}
}
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
Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;