Subarray within foreach loop php - php

I have this code here:
<?php foreach($blog_posts['post_category'] as $category) { ?>
How can I get this to work?
Basically I have a database with all my blog posts within them, one of the columns is post_category I'm trying to make a list out of all these by a foreach statement that gets the results like so:
$data['blog_categories'] = $this->db->query("SELECT `post_category` FROM `blog_posts`");
This is codeigniter by the way... Then in my view I have the code:
<?php foreach($blog_posts['post_category'] as $category) { ?>
I need to display each category in an li...

You wanna use implode I think
$output = array();
forreach($blog_posts['post_category'] as $item){
$output[] = "<li>$item</li>";
}
echo "<ul>".implode('',$output)."</ul>";
Or if you were just after the list items and not list just replace the last line with
echo implode('',$output);

Pretty sure what you're looking for is
$data['blog_categories'] = $this->db->query("SELECT DISTINCT `post_category` FROM `blog_posts`");
foreach ($data['blog_categories'] as $category) {
echo "<li>$category</li>";
}
Me, I'd change $data['blog_categories'] to just $blog_categories or something, but I kept it as you had it so as not to confuse the issue.

Related

Separating database results into categories

I have a MySQL database with a table called product. Columns are id, product_name, price, category. I use PDO with fetchAll and sort by category. I would like to create HTML tables for each category grouping. In the past I've always done something like this:
$category = "";
$html = "";
foreach($results as $row){
if ($row['category'] != $category){
if ($category != "")
$html .= "</table>";
$category = $row['category'];
$html .= "<table>";
}
//code for table row here
}
$html .= "</table>";
However, I am wondering if there is a different way to do this such as splitting an array by categories and running a foreach on each sub-array. Is this possible?
Edit:
To explain further, I am looking for something that is not as cumbersome. I prefer not having to check what the previous category was (or if it was empty). I prefer not having to specify a closing </table> tag twice. If an array can be split by category then this would get around these issues by just running a nested loop on each of the categories.
Edit 2:
For some reason this question was listed as opinion based. Can someone inform me as to what is opinion based about my question? I will then try to improve it.
If you wanted to skip the whole category check then yes, you could create a new array.
$productCategories = array();
foreach ($results as $result) {
$productCategories[$result['cat']][] = $result;
}
foreach ($productCategories as $productCategory) {
// Start table
foreach ($productCategory as $product) {
// Render product
}
// End table
}

Grab DB values and display For Each - Codeigniter

Having a bit of trouble getting my For Each function to display all the values from a DB into a view. Where am I going wrong? Not a back-end pro, nor did I write it. Database table is extremely simple, one column named id. I want to display each of the rows in my for each.
I have a custom MY_Controller.php file and in the _construct I have this, which fills in variables globally across the site.
$this->country_zones = $this->Studios_model->get_studios();
Model:
function get_studios()
{
//this will alphabetize them
$this->db->order_by('id', 'ASC');
$query = $this->db->get('gc_studio_zones');
foreach ($query->result() as $row)
{
$countries = $row->id;
}
return $countries;
}
In my view:
<?php foreach($this->$country_zones as $country):?>
<li><?php echo $country['countries']->id;?></li>
<?php endforeach;?>
Error:
Cannot access empty property...etc
I think you have a typo in your view regarding your loop variable, it should be this->country_zones:
<?php foreach($this->country_zones as $country):?>
<li><?php echo $country->id;?></a></li>
<?php endforeach;?>
Besides, your Model isn't returning an array, but only the last id. You need to push the values to your result array:
function get_studios()
{
//this will alphabetize them
$this->db->order_by('id', 'ASC');
$query = $this->db->get('gc_studio_zones');
$countries = array();
foreach ($query->result() as $row) {
$countries[] = $row;
}
return $countries;
}

Having difficulties with php foreach and passing by reference

I'm pulling some data from a database (with a function I have called query), and I want to add another key/value pair to each result, i.e.:
$items = query("SELECT * FROM items");
foreach($items as &$item) {
$item['fixedname'] = str_replace(' ','_',$item['name']);
}
Now I want to put these on an html view, i.e.:
<?php foreach($items as $item): ?>
<div id="<?= $item['fixedname'] ?>" ><?= $item['name'] ?></div>
<?php endforeach; ?>
However, this doesn't output correctly. For instance, when the query returns two items, the loop in the php outputs the same thing twice. If there are three: it outputs the first one, then two of the second one. What's the problem here?
When modifying using foreach() I've had weird results on occasion. I use
foreach ($items as $key=>$value) {
$items[$key] = modified($value);
}
Or, why not do it in the SQL SELECT your, fields, here, REPLACE(name, ' ', '-') AS fixedname
The data returned on the right side of the foreach is a copy of the data, it can't be modified directly. Instead you need to fetch both the $key (the ID of the item in the array) and the $item. By letting PHP telling you the $key you don't need to worry about whether the array is normal (e.g. having indexes of 0,1,2,...) and associative.
This example would walk the $items array and add 'fixedname' into it.
foreach($items as $key => $item) {
$items[$key]['fixedname'] = str_replace(' ','_',$item['name']);
}
You could do a normal for loop
<?php
for($i=0; $i < count($items); $i++){
$items[$i]['fixedname'] = str_replace(' ','_',$items[$i]['name']);
}
?>
Then everything will be ready when you go to your next foreach.
u have bunch of wrong things
1- dont use mysql , use PDO or mysqli instead
2- $items = query("SELECT * .... --->Call to undefined function query()
change it to
$items = mysql_query("SELECT * ....
3- Invalid argument supplied for foreach() ,
you missed to fetch your query
try this whole code
$items = mysql_query("SELECT * FROM items");
?>
<?php while ($row = mysql_fetch_array($items) ) {?>
<div id="<?php echo $row['fixedname'] ;?>" ><?php echo $row['name']; ?></div>
<?php } ?>

Multiple for loops - how to print data

i want to make a website something like popurls.com, but I will use static data stored in MySQL database. Btw I use php/mysql.
In each list i want to show around 10 links (just like on popurls). In that case, if I would have 20 lists, i would need to make 20 'for' loops (for each particular list).
My question is; is there some better way to print that 20 lists instead of using 20 'for' loops in php.
a for loop or a foreach loop will work fine, but it will be a lot less coding if you just create a single for loop and push content into an array of arrays or an array of strings... you can then do whatever you'd like with the actual content (assuming we're grouping by a column category. I'll use an example that uses an array of strings (and the query that I reference is explained here: http://explainextended.com/2009/03/06/advanced-row-sampling/)
$query = mysql_query([QUERY THAT GETS ALL ITEMS, BUT LIMITS BY EACH CATEGORY]) or die(mysql_error());
$all_items = array();
while($row=mysql_fetch_array($query)){
if (!isset($all_items[$row['category']])){ //if it isn't created yet, make it an empty string
$all_items[$row['category']] = "";
}
$all_items[$row['category']] .= "<li><a href='".$row['url']."'>".$row['title]."</a></li>"; //concatinate the new item to this list
}
Now we have an array where the block of HTML for each section is stored in an array keyed by the name of the category. To output each block, just:
echo $all_items['category name'];
PHP's foreach http://php.net/manual/en/control-structures.foreach.php
Depends a lot on your data input but I could imagine something like this:
<?php
$lists = arrray('list1', 'list2', 'list3');
foreach ($lists as $current) {
$data = fetch_data_from_mysql($current);
foreach ($data as $link) {
echo "Link";
}
}
function fetch_data_from_mysql($current)
{
$list_data = array();
// do whatever is required to fetch the list data for item $current from MySQL
// and store the data in $list_data
return $list_data;
}
You just need two foreach loops. Assuming that you take the data from a mysql table (like you wrote), this could be like this:
$list_query = mysql_query("SELECT * FROM lists";)
while( $list = mysql_fetch_array($list_query) )
{
echo "<h1>{$list['title']}</h1>";
$query = mysql_query("SELECT * FROM entries WHERE list_id = {$list['id']}");
while( $entry = mysql_fetch_array($query) )
{
echo "- {$entry['name']}<br />";
}
}
You can get all the information from the database and parse it into an array, something like
array[<news type1>] = array( link1, link2, link3, etc);
array[<news type2>] = array( link1, link2, link3, etc);
and so on
and on the layout you can use
foreach ($newsCategory AS $categoryLinks) {
foreach ($categoryLinks AS $newsLink) {
<show the link and / or extra data>
}
}
Just store your links in two-dimensional array. That way you'll have to make 1 outer loop (iterating over lists) and 1 inner loop iterating over links in a particular list.
$links = array(
'science' => array('link1', 'link2', ...),
'sports' => array('link1', 'link2'),
// ... and so on
);
foreach ($links as $category => $urls) {
echo "Links in category: $category\n";
foreach ($urls as $url) {
echo $url . "\n";
}
}

Creating multidimensional array containing database output

Im creating a website, where I make a foreach, that echos out some groups, containing checkboxes, with values and names. At the moment that data comes from a multidimensional array, but writing that array when adding new items, is slow, and not very user-friendly.
At the moment, my foreach looks like this:
echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';
/* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */
$totalID=0; // this is a counter we use to build our check box names
foreach ($items as $list){
$totalID++; // add one to the checkbox name counter
echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header
foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox
// $cbox now holds the item name, and point value
echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n";
}
}
echo "</form>";
And my array I write is something like this:
$items['computers']['title']='Computer Brand';
$items['computers']['items'][]=array('Apple iMac',1);
$items['computers']['items'][]=array('Apple Macbook',.5);
$items['phones']['title']='Phone Brand';
$items['phones']['items'][]=array('iPhone',1);
$items['phones']['items'][]=array('HTC',1);
As said, I can write this, but takes time.
I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do.
My current database looks like this:
http://i.stack.imgur.com/Rj0wQ.png
Anyone that have some tips how to do this easy, and also do it user friendly?
Thank you!
$sql = "SELECT category, title, brand, point FROM yourtable ORDER BY category, title";
$result = mysql_query($sql);
$data = array();
while(list($category, $title, $brand, $point) = mysql_fetch_array($result)) {
if (!isset($data[$category])) {
$data[$category] = array();
}
if (!isset($data[$category]['title'] && (!empty($title)) {
$data[$category]['title'] = $title;
}
if (!isset($data[$category]['items'])) {
$data[$category]['items'] = array();
}
$data[$category]['itemps'][] = array($brand, $point);
}
Your table is just screaming for some normalization, however. It's a horrendous construct.
Well if you dont' want to parse your result into a multi-dimensionnal array like you did before which would be the easiest task but you have to double de CPU work, there is one way i use often in this case:
No1: Make sure your result is sorted by "Category" and then sorted by whatever criteria you want to order your answers as.
No2: Initialize the "$current_category" to NULL
No3: Loop and detect new $categories and output the header as you go. Your script will look like this:
$currentcategory = NULL;
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
//Check for a category change
if($currentcategory != $row['category']){
echo '<h2>'.$row['title'].'</h2>'.PHP_EOL;
$currentcategory = $row['category'];
}
//Output the label
echo '<label class="checkbox"><input type="checkbox" name="totals'.$row['id'].' value="'.$row['point']'."> '.$row['brand'].'</label>'.PHP_EOL;
}

Categories