Foreach with Table - PHP and Leaguepedia API - php

I have this code to show how may times a champion was picked in a tournament for example ("Gragas : 2 Times" , "Syndra :4 times" , etc)
I'm using api from leaguepedia to recieve the informations
but im stucked right now, I'm having a problem when "echoing" my table to show the results.
So I want that "qtd" be by the "pick" side (Image1) and if there's an easy way to show what I want.
// $Result is a CURL coming from leaguepedia api
$result = json_decode($file_contents);
// Double foreach to access the values from leaguepedia api
foreach ($result as $d) {
foreach ($d as $data) {
// $data->title->Team1Picks is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So I need to explode to an array to count.
$picks[] = explode(",", $data->title->Team1Picks);
}
}
// $mostpicked is an array for me to count how many times a champion was picked
// $f is an array to see the names of the picked champions
foreach ($picks as $pick) {
foreach ($pick as $total) {
$mostPicked[] = $total;
$f[] = $total;
}
}
// Basically here I'm counting how many times a champion was picked Ex : ("Gragas:2","Syndra:4" ,etc)
asort($mostPicked);
$mostPicked = array_count_values($mostPicked);
$name = array_unique($f);
asort($name);
// Foreach to get all unique names from the picks Ex : ("Gragas","Shen",etc) instead of ("Gragas , "Gragas" , etc)
foreach ($name as $champ) {
echo "<tr>";
echo "<td>" . $champ . "</td>";
echo "</tr>";
}
// This foreach to get the number of times a pick was made Ex : ("Gragas 2 Times")
foreach ($mostPicked as $pick) {
echo "<tr>";
echo "<td>" . $pick . "</td>";
echo "</tr>";
}

Here you go, this should do it.
// Hero name => pick count
$heroPicks = array();
foreach ($result as $d) {
foreach ($d as $data) {
//$data->title->Team1Picks is coming from league pedia api as a string separated by "," Ex:("Gragas,Shen,Maokai,etc")
// So i need to explode to an array to count.
$picks = explode(",", $data->title->Team1Picks);
foreach ($picks as $pick) {
$pick = trim($pick);
if (!array_key_exists($pick, $heroPicks)) {
$heroPicks[$pick] = 0;
}
$heroPicks[$pick] += 1;
}
}
}
uasort($heroPicks, function($a, $b) {
return $a - $b;
});
$heroPicks = array_reverse($heroPicks);
echo "Best picks:".PHP_EOL."<br />";
foreach ($heroPicks as $heroName => $pickCount) {
echo $heroName." - ".$pickCount.PHP_EOL."<br />";
}

It seems because you're putting the $pick in a new <tr>
Try adjusting your loops so that you're building an array of $champ=>$qtd then you an iterate over that and build your table as desired.

Related

How can I echo the right key in my multidimensional associative array?

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);
}
}

PHP Add New Line to Array Values Inside One Row and Column in Database Table

I managed to add multiple data in one column in the database, but now I need to display it with a new line in the browser so they don't stick with each other as I display them as an array in one column.
Here is my code:
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subArray = array("StudentAnswer");
$subId6 = $db->get("answertable", null, $subArray);
foreach ($subId6 as $sub) {
$answers[] = $sub['StudentAnswer'] . "\n";
}
foreach ($answers as $row) {
$answers2 = explode("||", $row[0]);
foreach($answers2 as $row2){
$answers3 = $row2 . '\n';
}
}
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers3);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
You are overriding $subId6 after getting its content. Try to fetch the table $rows in a new variable and the extract the content from it, like the code below.
<?php
// Example of $subId6 content
$subId6 = array(["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]], ["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]]);
// Fetch rows
foreach ($subId6 as $sub) {
$rows[] = $sub['StudentAnswer'];
}
// Decode rows
foreach($rows as $row) {
$answers = explode("\n", $row[0]);
echo "New answers: \n";
// Split answers in single answer
foreach ($answers as $answer)
echo "$answer \n";
echo "\n";
}
You will have a list of all the answers split for table rows
If you want a string of answers seperated by a space then simply do
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subId6 = $db->get("answertable");
foreach ($subId6 as $sub) {
$answers .= $sub['StudentAnswer'] . ' ';
}
$answers= rtrim($answers, ' '); //remove last space in case thats an issue later
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}

Outputting odd and even number in array

Using below array, i'm trying to use foreach loop to iterate through each item. Then i need to apply if condition to check if the given number is even and odd. I also need to create two arrays one for even and one for odd and push each number in their respective category.
So i have done this so far:
These are the two arrays i created to push through the values to.
}
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if (value %2 == 0)
{
$array_even = $value;
echo $array_even;
}
else
{
$array_odd = $value;
echo $array_odd;
}
I'd like to know if i'm using the correct solution or are there major errors im committing?
It will surely work like charms.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if ($value %2 == 0)
{
$array_even[] = $value;
}
else
{
$array_odd[] = $value;
}
}
echo "<pre>";
print_r($array_odd);
echo "<pre>";
print_r($array_even);

Multiple json in one foreach

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>";
}
}

select a specific value from multi array by the first row

I'm pulling 3 colummns from one table and storing them in an array as such to populate a dropdown menu. The ref_code is used to decide which dropdown it will go to ('Module','Customer','Application') while id is the select value and ref_desc is the display text.
foreach ($test as $t) {
$aa[] = array($t->ref_code => array('id'=>$t->id, 'ref_desc'=>$t->ref_desc));
};
I've been trying to retrieve them using $aa['ref_code'] but have not been getting any success. Help please.
This question is similar, but I am unable to retrieve the values I want.
I found a solution on another forum but I will also give your solutions a try later. Thank you very much!
foreach ($aa as $a => $d) {
foreach ($d as $ref_code => $dd) {
echo "<p>". $ref_code ."</p>";
echo "<p>". $dd['ref_desc'] ."</p>";
echo "<p>". $dd['id'] ."</p>";
};
};
Why don't you write it like this? The ref_code (if it's unique) is the key of the array.
foreach ($test as $t) {
$aa[$t->ref_code] = array('id'=>$t->id, 'ref_desc'=>$t->ref_desc);
};
you need a three dimensional array:
dropdown => ids => displaytext
here we go:
// fill in:
$aa = array();
foreach ($test as $t) {
if ( !isset($aa[$t->ref_code]) )
$aa[$t->ref_code] = array();
$aa[$t->ref_code][$t->id] = $t->ref_desc;
};
// have a drop down:
$myDropDown = 'Customer';
foreach ( $aa[$myDropDown] as $id => $displaytext )
{
echo "<option value=\"" . $id . "\">" . $displaytext . "</option>";
}
.... etc.

Categories