I am using the code below to create a multi-dimensional array from a query so that I can organize the results by category but it only gets me 2 columns (category, agency).
I am not sure how I can alter this so that I can get 4 columns (category, agency, description, website). Any help is greatly appreciated.
$categories = array();
while ($row = mysqli_fetch_array($result))
{
$category = $row['category'];
$categories[$category][] = $row['agency'];
}
<?php
foreach ($categories as $category => $agencies)
{
?>
<h3><?php echo $category; ?></h3>
<table class="chart">
<?php
foreach ($agencies as $agency)
{
?>
<tr><td><?php echo $agency; ?></td></tr>
<?php
}
?>
</table>
<?php
}
?>
You could store the individual row results as an associative array:
$categories[$category][] = array(
'agency' => $row['agency'],
'description' => $row['description'],
'website' => $row['website']
);
Related
I have two databases tables called article_category and article_case. They are supposed to be combined in a webpage as below:
Article category[title]
Article category[description]
Article case[title]
Article case[contents]
Article case[title]
Article case[contents]
This should repeat itself using foreach until all article categories are populated on the page.
Each article_case will also use foreach, but it has to respect its 'category_id' value which matches the 'id' in article_category .
I'm having trouble filtering the article_case table so that it only picks up rows from its parent 'category_id'.
This is my current php code (which only makes an array of each table):
$this->db->select( "id,title,description" );
$this->db->from( 'article_category' );
$query_article_category = $this->db->get_compiled_select();
$query = $this->db->query( $query_sustainability_category . 'ORDER BY sort ASC ' );
foreach ($query->result_array() as $val) {
$data['article_category_posts'][$val['id']] = $val;}
$this->db->select( "id,category_id,title,contents" );
$this->db->from( 'article_case' );
$query_article_case = $this->db->get_compiled_select();
$query = $this->db->query( $query_article_case);
$data[ 'article_cases' ] = $query->result_array();
And here is my html:
<?php foreach ($article_category_posts as $key => $val) { ?>
<section>
<h2><?php echo $val['title']; ?></h2>
<p><?php echo $val['description']; ?></p>
</section>
<?php foreach ($article_cases as $key => $val) { ?>
<section>
<h3><?php echo $val['title']; ?></h3>
<p><?php echo $val['contents']; ?></p>
</section>
<?php } ?>
<?php } ?>
The current setup will input all article_cases disregarding the category_id.
How can I use foreach while assigning each article_case to their respective article_cateogry?
This would generate unnecessary amount of queries to the DB server.
The rly basic approach would be:
select all categories (as you have) SELECT * FORM a_category
for each category select cases SELECT * FROM a_case WHERE category_id = {$category['id']}
The second one is to combine the categories and cases right in the query with join and adjust the resulting data in php:
SELECT cat.title, cat.description, case.id AS case_id, case.category_id, case.title, case.content
FROM a_case case
INNER JOIN a_category cat ON cat.id = case.category_id
You can use a query to get all the records of article_case with related article_category.
group the query result by category_id.
$this->db->select("cat.title,cat.description,case.category_id,
case.title AS case_title, case.contents" );
$this->db->from( 'article_category cat');
$this->db->join('article_case case','case.category_id=cat.id');
$result=$this->db->get()->result_array();
$result_group = array_group_by($result, 'category_id');
array group by function
function array_group_by(array $array, $key)
{
if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
trigger_error('array_group_by(): The key should be a string, an integer, or a callback', E_USER_ERROR);
return NULL;
}
$func = (is_callable($key) ? $key : NULL);
$_key = $key;
// Load the new array, splitting by the target key
$grouped = [];
foreach ($array as $value) {
if (is_callable($func)) {
$key = call_user_func($func, $value);
} elseif (is_object($value) && isset($value->{$_key})) {
$key = $value->{$_key};
} elseif (isset($value[$_key])) {
$key = $value[$_key];
} else {
continue;
}
$grouped[$key][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$params = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('array_group_by', $params);
}
}
return $grouped;
}
in view you can show as below
<?php foreach ($result_group as $key => $cat_result) { ?>
<section>
<h2><?php echo $cat_result[0]['title']; ?></h2>
<p><?php echo $cat_result[0]['description']; ?></p>
<div class="box-bd-doted">
</section>
<?php foreach ($cat_result as $key => $val) { ?>
<section>
<h3 style="color:red"><?php echo $val['case_title']; ?></h3>
<p><?php echo $val['contents']; ?></p>
</section>
<?php }
}
?>
I have data like in the image below, Im using foreach loop to show my data.
But I want to show my data like his, I want to add "IC" to all elements of Ids..
This is my current code..
<?php
foreach ($model as $mod) { ?>
<tr>
<td><?= $mod['discount']; ?></td>
<td><?= $mod['ids']; ?></td>
</tr>
<?php } ?>
What do i need to do to add "IC" to $mod['ids'] for each row to be IC10000, IC100000, IC10000, IC10000.
As i commented out to use- Explode the ID's by , then concatenate the IC and again putback
$model = array(array('discount' => '2000', 'ids' => '100,1000,1000,1000'), array('discount' => '2001', 'ids' => '100,1000,1000,1000'),array('discount' => '2002', 'ids' => '100,1000,1000,1000'));
foreach ($model as $k=> $mod) {
$mod_2 = preg_filter('/^/', 'IC', explode(',', $mod['ids']));
echo $mod['discount'].'-'.implode(', ', $mod_2).PHP_EOL;
}
Example: https://3v4l.org/5I3l0
Through foreach loop you can do it !
PHP
<?php
$ids = "100,200,300,400,500,600";
$ids_array = explode(",",$ids);
$new_ids = array();
foreach($ids_array as $values){
$new_ids[] = "IC".$values;
}
echo implode(",",$new_ids);
?>
OUTPUT
IC100,IC200,IC300,IC400,IC500,IC600
I am trying to loop over an array but I keep getting the same error :/
Anyone has any idea what I'm doing wrong here?
my array:
$data[]= array('title' => get_the_title( $id ),
'link' => get_the_permalink( $id ));
My loop:
<?php foreach ($data as $item): ?>
<p><?php echo $item->title; ?></p>
<?php endforeach; ?>
I've dumped my array and it looks good so there's probably something wrong with my loop
As far as I can see you have an associative array with keys title and link so you don't have to call it like an object, simply do this..
<?php foreach ($data as $item): ?>
<p><?php echo $item['title']; ?></p>
<?php endforeach; ?>
You have to print data object first to look that in data object you have required data.
<?php
echo '<pre>';
print_r(data);
echo '</pre>';
?>
from that data object you can correct your foreach loop
Please use this foreach format
$data = array('title' => 5,
'link' => 5);
foreach ($data as $key => $value) {
echo $key;
}
I need to get the array_sum of $product['stars']; so I can use it to find the average. When I try to use it I am not using it on the array somehow? Also I believe this comes in as a string. Does it need to be converted to INT? Thanks so much for any ideas.
<?php
$categories = array();
while ($row_rsCategories = mysqli_fetch_assoc($res)) {
$product_array = array();
$product_array_query = mysqli_query($mysqli,"SELECT id, user_id, client_id, comments, stars FROM reviews WHERE user_id = '".$row_rsCategories['userId']."'");
while($product_array_fetch = mysqli_fetch_array($product_array_query)) {
$product_array[] = array("id"=>$product_array_fetch['user_id'],"comments"=>$product_array_fetch['comments'],"stars"=>$product_array_fetch['stars']);
}
$categories[] = array(
'id' => $row_rsCategories['userId'],
'name' => $row_rsCategories['usersName'],
'products' => $product_array,
);
}
foreach ($categories as $category) {
?>
<div class="col-md-4">
<div id = "user-square">
<div class="avatar">
<img src="<?php echo $avatarDir.$list['usersAvatar']; ?>" class="publicAvatar" />
</div>
<?php
echo $category['name']; ?> </br>
<?php foreach($category['products'] as $product) {
echo $product['stars']; ?> </br>
<?php }
?>
You could do it by combining array_sum with array_map:
$starsum = array_sum(array_map(function($x) { return $x['stars']; }, $product_array));
But you can also just calculate the sum while you're constructing the array of results:
$starsum = 0;
$rowcount = 0;
while($product_array_fetch = mysqli_fetch_array($product_array_query)) {
$product_array[] = array("id"=>$product_array_fetch['user_id'],"comments"=>$product_array_fetch['comments'],"stars"=>$product_array_fetch['stars']);
$starsum += $product_array_fetch['stars'];
$rowcount++;
}
$categories[] = array(
'id' => $row_rsCategories['userId'],
'name' => $row_rsCategories['usersName'],
'products' => $product_array,
'avgstars' => ($rowcount == 0) ? 0 : $starsum / $rowcount
);
There's no need to convert the values to integers, PHP will do that automatically when you use arithmetic functions on them.
I am trying to expand on my question asked here: Creating a multi-dimensional array from query
I have added a category description to my categories table but I cannot figure out how to add it to the code below and display each category description for each category.
Here is the code I am using to display the items by category:
$itemcategories = array();
while ($row = mysqli_fetch_array($result))
{
$head = $row['category'];
$itemcategories[$head][] = array(
'id' => $row['id'],
'title' => $row['title'],
'itemdesc' => $row['itemdesc'],
'price' => $row['price'],
'special' => $row['special']
);
}
<?php foreach ($itemcategories as $head => $items) { ?>
<h3><?php echo $head; ?></h3>
<table class="chart">
<?php foreach ($items as $item) { ?>
<tr><td><?php echo $item['itemdesc']; ?></td></tr>
<?php } ?>
</table>
<?php } ?>
// to initial variable holder
$categories = $items = array();
// looping mysql result
while ($row = mysqli_fetch_array($result))
{
// to get category name
$head = $row['category'];
// avoid excessive setting of $categories
if (!isset($categories[$head]))
{
$categories[$head] = $row['descrption'];
}
// assign mysql result to $items
$items[$head][] = $row;
}
// free mysql result
mysql_free_result($result);
// loop all $categories
foreach ($categories as $head=>$desc)
{
// this is my example for printing HTML
// you can use heredoc syntax
// or stick to your existing format
echo "<h3>{$head} - {$desc}</h3><table class="chart">";
foreach ($items[$head] as $item)
{
// print item description
echo "<tr><td>{$item['itemdesc']}</td></tr>";
}
echo "</table>";
}