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>";
}
Related
PHP 7.2
Wordpress 4.9.8
Advanced Custom Fields 5.7.7
I'm interested in creating an array where each item would hold:
post id
post title
array of images belonging to post
I am using an ACF repeater for every post that holds many images, the repeater name is carousel.
There is no connection between the WP post object and the ACF fields.
The issue:
nested foreach pushes all the images into the first post.
Expected:
nested foreach will fill the $randomArray only with images that belong to that post ID.
$workshop_posts_args = array(
'post_type' => 'workshops'
);
$randomArray = [
'post_id' => '',
'post_title' => '',
'post_image_url' => []
];
$post_query = new WP_Query($workshop_posts_args);
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$carousel_array = get_field('carousel', get_the_ID());
echo "<h2>".get_the_title()."</h2>";
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray['post_id'] = get_the_ID();
$randomArray['post_title'] = get_the_title();
$randomArray['post_image_url'][] = $image['url'];
echo 'image_url:'.$image['url'].'<br>The array: <pre>'.print_r($randomArray, true).'</pre>';
?>
<?php
}
}
}
}
}
?>
<h1>TOTAL ARRAY</h1>
<pre><?php print_r($randomArray) ?></pre>
You are over-writing array index again and again inside loop and that's you problem.
so do:-
$randomArray = []; //before post_query
And change if block like below:-
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$id = get_the_ID();
$randomArray[$id]['post_id'] = $id;
$randomArray[$id]['post_title'] = get_the_title();
$carousel_array = get_field('carousel', $id);
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray[$id]['post_image_url'][] = $image['url'];
?>
<?php
}
}
}
}
}
Note:- rest code will be same
the above code will give you post-id based multi-dimensional array. if you want indexes to be 0,1,2,3..... format then do:-
$randomArray = array_values($randomArray);
Use proper indexing of $randomArray like below:
<?php
$workshop_posts_args = array(
'post_type' => 'workshops'
);
$randomArray = array();
$post_query = new WP_Query($workshop_posts_args);
$index = 0;
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$randomArray[$index]['post_id'] = get_the_ID();
$randomArray[$index]['post_title'] = get_the_title();
$carousel_array = get_field('carousel', get_the_ID());
//echo "<h2>".get_the_title()."</h2>";
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray[$index]['post_image_url'][] = $image['url'];
//echo 'image_url:'.$image['url'].'<br>The array: <pre>'.print_r($randomArray, true).'</pre>';
?>
<?php
}
}
}
$index++;
}
}
?>
<h1>TOTAL ARRAY</h1>
<pre><?php print_r($randomArray) ?></pre>
I have a foreach loop and have a problem with it. My loop show duplicate some item and I want show item only once and don't duplicate item. My loop it is.
foreach($result as $res){
$id = $res->id;
$title = $res->title;
echo $title;
}
$partial=array();
foreach($result as $res){
if (!in_array($res->id, $partial)) {
$id = $res->id;
$title = $res->title;
echo $title;
array_push($partial, $res->id);
}
}
try this one..
$present_array = array();
foreach($result as $res){
if(!in_array($res->title, $present_array)){
$present_array[] = $res->title;
$id = $res->id;
$title = $res->title;
echo $title;
}
}
<?php
function remove_dup($matriz) {
$aux_ini=array();
$entrega=array();
for($n=0;$n<count($matriz);$n++)
{
$aux_ini[]=serialize($matriz[$n]);
}
$mat=array_unique($aux_ini);
for($n=0;$n<count($matriz);$n++)
{
$entrega[]=unserialize($mat[$n]);
}
return $entrega;
}
foreach(remove_dup($result) as $res){
$id = $res->id;
$title = $res->title;
echo $title;
}
another solution is, if you are getting this data from database then use DISTINCT in your select query.
Do a fast check & make your code execute faster like this:
$check_dup = array();
foreach ($items as $item){
if (in_array($item['id'], $check_dup))
continue;
else {
array_push($check_dup, $item['sid']);
/* your code in foreach loop */
}
}
Try this:
$result = array(
array(
'id' => "1",
'title' => "My title"
),
array(
'id' => "2",
'title' => "My title 2"
)
);
foreach($result as $res){
$id = $res['id'];
$title = $res['title'];
echo $title . "<br>";
}
This page contains the following errors:
error on line 1 at column 462: Opening and ending tag mismatch: post line 0 and row1
Below is a rendering of the page up to the first error.
Now how to understand column 462 in my code?
It appears that all of your code is written on one line for "micro-optimization" purposes. Unfortunately this hurts readability a tremendous amount.
Please turn this:
<?php include("connect.php"); $result=mysql_query("SELECT * FROM category "); /* create one master array of the records */ $posts = array(); if(mysql_num_rows($result)) { while($post = mysql_fetch_assoc($result)) { $k=0; $a=$post['id']; $result2= mysql_query("SELECT image,price,quantity FROM flower where $a = flower.id"); $postin = array(); if(mysql_num_rows($result2)) { while($row1 = mysql_fetch_assoc($result2)) { $postin[] = array( 'row1' => $row1); }} $posts[]=array( //$posts[] = array('post'=>$post); 'post' => $post ); } }header('Content-type: text/xml'); echo '<Details>'; foreach($posts as $index => $post) { if(is_array($post)) { foreach($post as $key => $value) { echo '<',$key,'>'; if(is_array($value)) { foreach($value as $tag => $val) { echo '<',$tag,'>',htmlentities($val),'</',$tag,'>'; } foreach($postin as $index => $row1) { if(is_array($row1)) { foreach($row1 as $key => $value) { echo '<',$key,'>'; if(is_array($value)) { foreach($value as $tag => $val) { echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';}} echo '</',$key,'>';}}}} echo '</',$key,'>';}}} echo '</Details>';?>
Into something that looks like this:
<?php
include("connect.php");
$result=mysql_query("SELECT * FROM category "); /* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)){
// A LOT OF CODE
}
?>
Make sure to create new lines and indent when necessary. Please edit your initial question if possible with new code, or create a new question.
thank you
I am using the cms perch to retrieve data using various functions. I am retrieving product items from various sub pages. The code I have so far is working as it should and can be seen here: http://www.ww.thirdfloordesign.net/products/70mm-couplers/
$raw = perch_pages_navigation(array(
'from-path'=>'*',
'skip-template'=>true
));
if (count($raw)) {
$items = $raw;
} else {
// add else statement to output warning 'no products found in this category' or something
}
foreach($items as $item) {
$product['ID'] = $item['pageNavText'];
$product['title'] = $item['pageTitle'];
$product['path'] = $item['pagePath'];
$product['parent'] = $item['pageSubpagePath'];
PerchSystem::set_vars(array(
'product-id'=>$product['ID'],
'product-title'=>$product['title'],
'product-path'=>$product['path'],
'product-parent'=>$product['parent']
));
$product['image'] = perch_content_custom('Image', array(
'page'=>$product['path'],
'template'=>'product/_image.html',
'sort'=>'_order',
'count'=>1
), true);
PerchSystem::set_var('product-image', $product['image']);
$items[] = perch_content_custom('Product', array(
'page'=>$product['path'],
'template'=>'product/_product.html'
), true);
}
Where the data needs to be outputted I am using the following code and it seems to be working as it should except it is also echoing an array which can be seen on the page. Is it because I am using duplicate $variables / array names? Solutions please
<?php
if (!empty($items)) {
?>
<ul class="product-grid">
<?php
foreach($items as $item) {
echo $item;
}
?>
</ul>
<?php
} else {
?>
<p class="alert alert-warning"><i class="icon-warning-sign"></i>No products found!</p>
<?php } ?>
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']
);