Foreach is showing only one result instead of all - php

I'm trying to select elements from only one category and show them on page.
Currently I have 5 posts in this category but on page I see only one.
Why is that?
Here is how I try
<?php
$args = array(
'showposts'=>-1,
'category_name' => 'custom-page',
);
$query = new WP_Query( $args );
$aSolutionsePost = array();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$aSolutionsePost = array();
$query->the_post();
$aSolutionsePost['title'] = $query->post->post_title;
$aSolutionsePost['content'] = $query->post->post_content;
}
}
?>
<div class="col-4 ">
<ul class="price">
<?php if(!empty($aSolutionsePost)){?>
<?php foreach($aSolutionsePost as $item){ ?>
<li class="header"><?php echo $item->title; ?></li>
<li class="grey"><?php echo apply_filters('the_content',$item->content);?></li>
<?php }?>
<?php }?>
</ul>
</div>
When I print_r($aSolutionsePost); I see only one result. This:
Array (
[title] => Price test title
[content] => Price test content
[0] => Array (
[title] => Price test title
[content] => Price test content
)
)

This line of code inside your while ( $query->have_posts() ) loop:
$aSolutionsePost = array();
is overwriting the value of $aSolutionsePost each pass through the loop. You probably want something like this instead:
while ( $query->have_posts() ) {
$query->the_post();
$aSolutionsePost[] = array('title' => $query->post->post_title,
'content' => $query->post->post_content);
}
Note that in your code to echo the results, you are treating the array elements as objects, not associative arrays. It's simplest to just change those lines to this:
<li class="header"><?php echo $item['title']; ?></li>
<li class="grey"><?php echo apply_filters('the_content',$item['content']);?></li>
but if you want to keep that code the same you can change the assignment line to this:
$aSolutionsePost[] = (object)array('title' => $query->post->post_title,
'content' => $query->post->post_content);

Check array set inside while,
You re-create $aSolutionsePost every time, so it will be reseted.
Solution is to create new array and append it to $aSolutionsePost, check below snippet.
while ( $query->have_posts() ) {
$tmpSolutionsePost = array();
$query->the_post();
$tmpSolutionsePost['title'] = $query->post->post_title;
$tmpSolutionsePost['content'] = $query->post->post_content;
$aSolutionsePost[] = $tmpSolutionsePost;
}

You are actually updating the same array with new values in the loop.
$finalData =array();
while ( $query->have_posts() ) {
$aSolutionsePost = array();
$query->the_post();
$aSolutionsePost['title'] = $query->post->post_title;
$aSolutionsePost['content'] = $query->post->post_content;
$finalData[] = $aSolutionsePost;
}
Now iterate over $finalData.

This is because you are adding the element to same key of array again and again and that is why there is only 1 element in the array, hence foreach is showing only 1 element.
You should possibly take 2d array to solve this purpose.

Related

Simple array lookup

I have an array, $persons
When I execute: print_r($persons) I get:
(
[0] => 30131
[1] => 29763
)
The two five-digit numbers are IDs for two posts in a CPT called people
How do I iterate through the array and print the title of each post?
My best guess returns nothing:
foreach( $persons as $person ):
$title = get_the_title( $person->ID );
$peopleout .= $title . ', ' ;
endforeach;
echo $peopleout
Judging from your first snippet, $person inside your loop is a single value, not an object.
That means you should change the $title = lines to this:
$title = get_the_title($person);
Also, you will currently be adding an extra comma at the end of the string. To resolve this, I would add the title to an array, then implode that array to echo the values. That would look like this;
$peopleout = [];
foreach( $persons as $person ):
$peopleout[] = get_the_title($person);
endforeach;
echo implode(", ", $peopleout);
$person is no object, so keep it plain as it contains the ID.
$title = get_the_title($person);
Just for fun you can do all of this as a one-liner.
echo implode(', ', array_map(fn($id) => get_the_title($id), $persons));

PHP: Prevent repeating nested foreach multidimensional array

I have been trying to loop nested foreach loops but the problem is first foreach loop records repeating as the count of second foreach loop
first array is coming from mysql data and second array I have wrote below, In my case i want to loop the color presets in second array with first foreach loop results. I'm not much good in arrays please help me to solve this issue.
here is the second array and code :
$colors = array (
0 => array ("id"=> 0, "dark" => "#16a085", "light" => "#1ABC9C"),
1 => array ("id"=> 1, "dark" => "#2980B9", "light" => "#3498DB "),
);
$unique = array_unique($colors, SORT_REGULAR);
foreach ($skill as $skilldata) {
foreach ($unique as $key => $val) {
<div class="skillbar clearfix " data-percent="<?php echo $skilldata['js_skill_perc'].'%'; ?>">
<div class="skillbar-title" style="background: <?php echo $val['dark']?>;">
<span><?php echo $skilldata['js_skill_title']; ?></span></div>
<div class="skillbar-bar" style="background-color: <?php echo $val['light']?>; width: <?php echo $skilldata['js_skill_perc'].'%'; ?>;"></div>
<div class="skill-bar-percent"><?php echo $skilldata['js_skill_perc'].'%'; ?></div>
</div>
<?php }} ?>
Output should be like : HTML5 (green) PHP(blue) and SEO (green)
but this is how output looks like:
If You need to just switch the colors from line to line, You can use CSS for this (see :nth-child(even) and :nth-child(odd)) or do it in PHP like this:
$colors = array(
...
);
$colors_count = count($colors);
$colors_index = 0;
foreach ($skill as $skilldata) {
$color = $colors[$colors_index % $colors_count];
$colors_index++;
echo ... whatever using $color ...
}

Add class to ACF multi select

I have been struggling for two hours with the following situation and I still didn't find the solution. Hopefully you guys can help me out. It's about the following:
I use ACF to make a selection from a multi select menu. I want to show all of the choices and I want to add a class to the selected values.
Below you will find my code so far. This outputs all of the choices. But I don't know how to check whether the choice has been selected or not.
$features = get_field_object('features');
$choices = $features['choices'];
$values = $features['value'];
if ( $features ):
echo '<ul class="checks">';
foreach ( $choices as $choice) {
echo '<li>'. $choice .'</li>';
}
echo '</ul>';
endif;
Thanks a lot for helping!
You can check if the key of the current $choice is as a value in the $values array.
if you var_dump the $features array you will see that $values array contains the keys of the values and the $choices array contains both of them.
var_dump example:
$features['value'] => Array
(
[0] => color1
)
$features['choices'] => Array
(
[color1] => red
[color2] => yellow
[color3] => green
)
Code:
$features = get_field_object('features');
$choices = $features['choices'];
$values = $features['value'];
if ( $features ):
echo '<ul class="checks">';
foreach ( $choices as $key => $choice) {
$class = in_array($key, $values) ? 'class="selected"' : '';
echo '<li ' . $class . '>'. $choice .'</li>';
}
echo '</ul>';
endif;

PHP nested foreach generating duplicates

I know this has been posted a million times over but I cant find an example where the same item was being called for the same use but with different values. I am using lightbox and I need my <a> to pull in the size=full and my <img> to pull in the size=thumbnail. I am successfully doing this but my nested foreach statements are casing duplicates.
<?php
$dyno_images = rwmb_meta( 'gallery-images', 'type=image_advanced&size=thumbnail' );
$dyno_images_lrg = rwmb_meta( 'gallery-images', 'type=plupload_image&size=full' );
?>
<?php
foreach ( $dyno_images_lrg as $dyno_image_lrg ) {
foreach ( $dyno_images as $dyno_image ) {
echo '<figure class="gallery-item"><div class="gallery-icon landscape"><img src="'.$dyno_image['url'].'" aria-describedby="gallery-1-584" class="attachment-full"></div></figure>';
}
}
?>
I assume that each item in $dyno_images_lrg corresponds to an item in $dyno_images.
In that case you only want to loop once and pick out the corresponding item:
foreach ( $dyno_images_lrg as $key => $dyno_image_lrg ) {
$dyno_image = $dyno_images[$key];
//Snipped for brevity - rest of the code should remain the same
}

Handling foreach with key and value in php

I have a $row array that will print the below array
Array
(
[BookCode] => 124
[BookName] => Book1
)
Array
(
[BookCode] => 123
[BookName] => Book2
)
...........
I have a code like this:
<?php foreach($row as $key=>$value){ ?>
<span style="color:red;font-weight:bold;"><?php echo $value; ?></span>
<?php } ?>
But I'm not able to get the BookCode in my anchor tag since I'm using foreach with key-value. In my case I have to use foreach only (as intructed by my client)
So how can I get the value inside the anchor tag?
Your foreach loop is not returning what you expect—you have an array of associative arrays.
<? foreach ( $row as $column ): ?>
<a href="process.php?bcode=<?=$column['BookCode']?>">
<? endforeach; ?>
In the above, the link will be process.php?bcode=124
Alternatively, if you really want to use the $key=>$value:
<? foreach ( $row as $column ): ?>
<? foreach ( $column as $key=>$value ) ?> // here $key = 'BookCode'
<a href="process.php?bcode=<?=$value?>">
<? endforeach; ?>
<? endforeach; ?>
Try foreach like this. It may help to you
foreach($row as $data)
{?>
<?php } ?>

Categories