Handling foreach with key and value in php - 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 } ?>

Related

Foreach is showing only one result instead of all

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.

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 ...
}

Iterating through foreach loop - group sorting effiiceny

I have a loop running in my project that I am not happy with and wondered if there is a more efficient way of achieving this?
I have an array like so
$myarray = ["value1", "value2", "value3"];
Then I want to go through another object ($sponsors) and only print out values on that has a field that matches the value in $myarray[]. Like so:
<?php foreach ($myarray as $value): ?>
<?php foreach ($sponsors as $post) : setup_postdata( $post );?>
<?php if($post['someValue'] == $value): ?>
//Do the work
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
This is working fine, but it might mean 50-60 loops just to grab and print out a few bits of markup. Is there a better way to do this?
EDIT NOTE: (based on initial replies) The order of the $myarray is important, this allows me to group the 'value1' together and then 'value2' etc
You can get rid of outer foreach loop
<?php foreach ($sponsors as $post) : setup_postdata( $post );?>
<?php if(in_array($post['someValue'], $myarray)): ?>
//Do the work
<?php endif; ?>
<?php endforeach; ?>
UPDATE
Given $sponsers is an array of posts, You can improve peformance by filterig posts based on some value by native array_filter() function So there are less posts for foreach to iterate over.
After this there is no need for if statement which will also improve performance.
<?php foreach ($myarray as $value): ?>
<?php $filteredPosts = array_filter($sponsors, function($post) use ($value) { return $post['someValue'] == $value; }); ?>
<?php foreach ($filteredPosts as $post) : setup_postdata( $post );?>
// do something
<?php endforeach; ?>
<?php endforeach; ?>
use in_array
ref in_array from here
<?php
foreach ($sponsors as $post) {
setup_postdata( $post );
if(in_array($post['someValue'],$myarray){
//Do the work
}
}
?>
Use in_array function
it takes three parameter but one is optional
for e.g. :
in_array($value, $myarray )

object foreach loop iterate only even values

Basically I have a set of object values I want render in 2 separate html lists
I figure the simplest way to do this is by displaying evens only in one list, and odd only in the other
Here is the current code for displaying a single list
<ul>
<?php foreach ($values as $value) : ?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
</ul>
Try this:
<ul>
<?php
/* read the index key */
foreach ($values as $key => $value) :
/* skip the current element if it doesn't have an even index */
if($key % 2 == 1) continue;
?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
You didn't specify if the array has integer index. So I use a separate index pivot. This will do.
$v=array();
$index = 1;
foreach ($values as $value){
$v[($index++)%2][]=$value->value;
}
list ($evens, $odds) = $v;
echo "<ul><li>".implode("</li><li>", $odds)."</li></ul>"; // show list of odds
echo "<ul><li>".implode("</li><li>", $evens)."</li></ul>"; // shows list of even

PHP foreach loop through multidimensional array

I have an multidimensional array, how can I use it? I want to use each separate array in a for loop.
What I want to achive is to be able to put each part in my database like
entry in db no. 0 -> 1 and 4
entry in db no. 1 -> 5 and 6
entry in db no. 2 -> 1 and 4 and 5 and 6
I have this code:
<?php
print_r($calculatie_id);
for ($i=0; $i<=3; $i++)
{
?>
<tr>
<td>
<?php
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
?>
print_r($calculatie_id); gives
Array ( [0] => Array ( [0] => 4 [1] => 6 ) [1] => Array ( [0] => 1 [1] => 5 ) [2] => Array ( [0] => 5 [1] => 6 ) [3] => )
But when using the foreach I only get 46
Some extra information:
This array is created by an multiple select in an for loop. Any other suggestions are welcome.
for ($i=0; $i<=$aantal_regels_corr; $i++)
{
?>
<tr>
<td>
<?php
// maak select name
$calculatie_id = 'calculatie_id'.$i;
// rest van formulier
if($error_vergeten[$i] == "ja"){ $error_omschr = $error_omschr_vergeten[$i]; include('includes/input_error.php'); } ?> <textarea rows="7" cols="80" name="omschrijving[]" /><?php echo $omschrijving[$i]; ?></textarea>
</td>
<td colspan="2">
<select multiple="multiple" width="50" size="7" name="<?php echo $calculatie_id ?>[]" style="width: 150px">
<?php
$sql_calc = "select id, naam, actief from sp_calculatie WHERE (offerte_id = '".$row['off_offerte']."' OR offerte_id = '".$offerte_id."') AND actief = 'ja' ORDER BY id ASC";
$res_calc = mysql_query($sql_calc,$con);
while ($row_calc = mysql_fetch_assoc($res_calc)){
?>
<option value="<?php echo $row_calc["id"] ?>"><?php if (empty($row_calc["naam"])) { echo $row_calc["id"]; } else { echo $row_calc["naam"]; } ?></option>
<?php } ?></select>
</td>
</tr>
<?php } ?>
foreach($calculatie_id as $inner_arr)
foreach($inner_arr as $value)
echo $value;
Edit: you should try to learn and understand what's going on here. Then, you can do whatever you want with the code I wrote. You said: gives 14561456 I want to use $calculatie_id0=14 $calculatie_id1=56 $calculatie_id2=1456 etc Then, you will have to do something like this:
foreach($calculatie_id as $index => $inner_arr){
echo "$calculatie_id$index = "
foreach($inner_arr as $value)
echo $value;
echo "<br/>";
}
Or you can create those variables you want (which does not make any sense for me):
foreach($calculatie_id as $index => $inner_arr){
${"calculatie_id$index"} = '';
foreach($inner_arr as $value)
${"calculatie_id$index"} .= $value;
echo ${"calculatie_id$index"}."<br/>";
}
Basically what you have is an array like this:
array(
array(
data
)
)
All you need is:
foreach($yourArray as $innerArray)
foreach($innerArray as $value)
echo $value;
That will output what you want. I'm not particularly sure why you're doing a for() loop then a foreach.
You need to nest your foreach loops (so you have a loop inside a loop)
You could try:
foreach ($calculatie_id as $key => $value) {
echo "$calculatie_id:".$key;
for ($i=0;$i<=count($value);$i++) {
echo $value[$i];
}
}
I don't understand why your original code snippet isn't working. Could it be the fact that $calculatie_id[3] is not an array?
I tried this:
<?php
$calculatie_id = array ( array(4,6), array(1,5), array(5,6), '' );
for ($i=0; $i<=3; $i++)
{
if(!is_array($calculatie_id[$i]))
continue;
echo "$i: ";
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
echo '<br/>';
}
And that prints:
0: 46
1: 15
2: 56
Many thanks for helping me out this far but all the examples I try to implement are not working.
I have been trying this script for over 2 weeks now. It seems I'm going all the wrong way.
I have put my code online at www.pws.nl/downloads/sp_offerte_add.rar. It must be easier then what I'm writing in the code right now.

Categories