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);
}
}
Related
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.
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);
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 m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}
I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}