How can I re-organize php array of sports - php

I'm trying to list sport league offerings for intramurals. My current php foreach spits out all the leagues and offerings. Great.
Now I want to only show 1 instance of the sport (course), like "Basketball" and then list the multiple league offerings (offering) in columns.
I can't do another loop based on
if $nt['course'] == "Basketball" because these will change
Not sure if my mssql query needs to change or if I can use another foreach loop?
query
$sql2 = SELECT category
,course
,offering
,Semester
,spots
,registerLink from dbtable WHERE semester like "%Fall 2016%" and category like "%Leagues%" ORDER BY course
$rs= mssql_query ($sql2, $con)
or die("Error!");
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
$result[] = $row;
}
}
return $result;
exit();
my foreach loop in view:
<?php
foreach ($data as $nt) {
echo "<div class='col-md-2'>";
echo "<h2><a href='#'>".$nt['course']."</a></h2>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
So just to clarify:
category = "Leagues" which is in my query
course = Basketball and Flag Football, etc

It's very simple:-
instead of
$result[] = $row;
do
$result[ $row['course']][] = $row;

Simple solution:
$result = array();
if (mssql_num_rows($rs)) {
while ($row = mssql_fetch_assoc($rs)) {
if(!in_array($row["course"], $result))
{
array_push($result, $row["course"]);
}
array_push($result[$row["course"]], $row);
}
}
return $result;
And loop in view:
foreach($data as $key => $value)
{
echo "<h1>".$key."</h1>";
foreach($value as $nt)
{
echo "<div class='col-md-2'>";
echo "<h3>".$nt['offering']."</h3>";
echo "<h4>".$nt['Semester']."</h4>";
echo "<p>".$nt['spots']."</p>";
echo "<button>".$nt['registerLink']."</button>";
echo "</div>";
}
}

Related

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

PHP foreach and returning unique headers from table rows

What I want to happen is... I know that an if goes in the the foreach but I cannot seem to get to work. Please help me.
GDESCRIP
code, descrip
code, descrip
code, descrip
GDESCRIP
code, descrip
code, descrip
code, descrip
$query = "Select gdescrip, code, descrip from sometable group by gdescrip order by code";
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array())
{
$rows[$row['gdescrip']][] = $row['code'];
}
foreach($rows as $key => $category)
echo '<strong>' .$key. '</strong><br />';
foreach($category as $item)
{
echo '<input type="radio" name="'.$item.'">' . $item .' </input><br/>';
}
}
else {
echo "0 results";
}
You're not putting $row['descrip'] into $rows. The simplest way to do that is to add another dimension to $rows, and put the whole row returned from the query into that dimension.
while ($row = $result->fetch_array()) {
$rows[$row['gdescrip'][] = $row;
}
The second foreach loop needs to be nested inside the first one.
foreach ($rows as $key => $category) {
echo "<strong>$key</strong><br/>";
foreach ($category as $item) {
echo "<input type='radio' name='{$item['code']}'>{$item['code']} {$item['descrip']}<br/>";
}
}
And there's no such thing as </input>; <input> is self-closing, it doesn't contain other elements.
Here is what I was able to get working. Obviously it is not mysqli but apparently I just don't know enough about mysqli to change this script so that it does work. Someone please feel free to point out where I am missing the mysqli conversion. Thank you in advance for your knowledge.
$categories = array();
$result = select statement;
while($row = mysql_fetch_assoc($result)){
$categories[$row['gdescrip']][] = $row;
}
foreach($categories as $key => $category){
echo '<strong>' .$key. '</strong><br/>';
foreach($category as $item){
$key = str_replace(' ',"_",$key);
echo '<input type="radio" name="'.$key.'" value="'.$item['code'].'">' .$item['code'] . $item['DESCRIP'] . '<br/>';
}
}

How to get more than 20 results for nearby places using google api

<?php
{
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
echo "next token".$dataArray->next_page_token."<br>";
if(!empty($dataArray->next_page_token)) {
echo "in the if statement"."<br>";
$placeSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=10000&types=mosque&sensor=true&key=AIzaSyASP02W3Qwb75Ruep3isiGstqA7Y2HXjGw&nextpage=".$dataArray->next_page_token;
$placeSearchJSON = file_get_contents($placeSearchURL);
//echo "hello";
$dataArray = json_decode($placeSearchJSON);
if(isset($dataArray->status) &&$dataArray->status == "OK") {
foreach( $dataArray->results as $details) {
array_push($references, $details->reference);
array_push($names, $details->name);
}
}
echo "hello<br>";
}
foreach ($names as $name) {
echo $name."<br>";
}
?>
I get the same 20 results every time, and I have used pagination as you can see in my code. Every time I print the next page token I get a different one.
I would really appreciate if someone could point out the error in my code because I am stuck with this for quite some time. You are also most welcome to give any kind of relevant suggestion.
use pagetoken instead of nextpage in your url string and in the last two calls give only api key and page token as parameter and after each api call use sleep(2) i tried your code and it works perfectly when the following changes are made.happy coding!
<?php
//echo"hello";
$references = array();
$names = array();
$lat="26.177194999999998";
$long="91.77591333333334";
$count=0;
$placeSearchURL ="https://maps.googleapis.com/maps/api/place/radarsearch/json?location=26.177194999999998,91.77591333333334&radius=3000&types=mosque&key=your APIkey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
foreach( $dataArray->results as $details) {
//echo $details->place_id;
array_push($references, $details->place_id);
}
foreach($references as $reference)
{
$count=$count+1;
//echo $count." ";
$placeSearchURL="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$reference."&key=your apikey";
$placeSearchJSON = file_get_contents($placeSearchURL);
$dataArray = json_decode($placeSearchJSON);
echo $dataArray->result->name."<br>";
echo "lat ".$dataArray->result->geometry->location->lat."<br>";
echo "lon ".$dataArray->result->geometry->location->lng."<br>";
echo "address ".$dataArray->result->formatted_address."<br>";
echo "<br>";
}
?>
basically i wanted to find a way to get more than 20 places of type masjid so i first used radar search to get placeids and then for each placed_id got the information and best part is you can get arount 200 results of nearby places

PHP Multidimensional object menu

I have made function to get multidemnsional menu from database.
public function get_menu($parent=0,$vis=1) {
$categories = array();
$this->db->from('ci_categories');
$this->db->where('cat_child',$parent);
$this->db->where('cat_vis',1);
$this->db->order_by('cat_order');
$q = $this->db->get();
$result = $q->result();
$i=0;
foreach($result as $mainCategory) {
$mainCategory->cat_subcategories = $this->get_menu($mainCategory->cat_id);
$categories[$i] = $mainCategory;
$i++;
}
return $categories;
}
It is working but I would like to print out the menus. For now I can print main menu and one child with this code:
if (count($menu) > 0) {
foreach($menu as $menu_item) {
$link = anchor("category/".$menu_item->cat_url, $menu_item->cat_name);
echo "<li>$link";
if (!empty($menu_item->cat_subcategories)) {
echo "<ul>";
foreach($menu_item->cat_subcategories as $subcat) {
$sub_link = anchor("category/".$subcat->cat_url, $subcat->cat_name);
echo "<li>$sub_link</li>";
}
echo "</ul>";
}
echo "</li>";
}
}
It is working too but how could I print out even 3rd or 4th submenu without manualy writing those foreach and ifs ? Thanks
You can try a recursive function...
Something like:
function showMenu($menu) {
echo "<ul>";
foreach ($menu as $menu_item) {
$link = anchor("category/".$menu_item->cat_url, $menu_item->cat_name);
echo "<li>$link";
if (!empty($menu_item->cat_subcategories)) showMenu($menu_item->cat_subcategories);
echo "</li>";
}
echo "</ul>";
}
That's an idea ;)

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories