php storing variables for use outside a for loop - php

I have the following for loop:
<?php foreach($this->relatedItems as $key=>$item): ?>
<div class="column1"><?php echo $item->extraFields->field1->value; ?></div>
<div class="column2"><?php echo $item->extraFields->field2->value; ?></div>
<div class="column3"><?php echo $item->extraFields->field3->value; ?></div>
<?php endforeach; ?>
Id like to create a variable for each custom field for each related item passed, for use outside of the loop.
Ideally I would have variables:
relatedItems1_field1,
relatedItems1_field2,
relatedItems1_field3,
relatedItems1_field4,
relatedItems2_field1,
relatedItems2_field2,
relatedItems2_field3,
relatedItems2_field4,
relatedItems3_field1,
relatedItems3_field2,
relatedItems3_field3,
relatedItems3_field4
Any assistance would be much appreciated, many thanks in advance!

Alternative 1
As long as $this->relatedItems isn't an associative array (having keys that aren't in sequence or strings as key), then you can use this outside the loop:
$this->relatedItems[0]->extraFields->field1->value
Alternative 2
If the array keys in the $this->relatedItems are unpredictable/associative, you can use this code:
<?php
$keys = [];
foreach($this->relatedItems as $key => $item):
$keys[] = $key;
?>
<div class="column1"><?php echo $item->extraFields->field1->value; ?></div>
<div class="column2"><?php echo $item->extraFields->field2->value; ?></div>
<div class="column3"><?php echo $item->extraFields->field3->value; ?></div>
<?php
endforeach;
?>
This will create an array with all the keys (0-9, if you have 10 array items in the $this->relatedItems).
Then you can use this outside the loop:
$this->relatedItems[$keys[0]]->extraFields->field1->value
No need to copy all the values to new variables, since you already have them in your scope.

You can use multi dimensional arrays for storing values
Check out the example code.
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
) ;
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>
Like this
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);

Related

Loop after all elements in wordpress custom field

I'm using Types Fields form Toolset Plugin for Wordpress, and I've got simple custom post type with few checkoboxes. I'm rendering checked values by:
<?php
$partners = types_render_field("partners", array('normal' => true));
?>
<?php echo($partners); ?>
output looks like this:
value1, value2, value3
The question is how can I loop after all elements in $partners, to manage this output:
<div class="value1"></div>
<div class="value2"></div>
<div class="value3"></div>
Explode your string then use php foreach short syntax :
$partners = explode(', ', $partners);
<?php foreach ($partners as $partner) : ?>
<div class="<?= $parner ?>"></div>
<?php endforeach; ?>
Final working version:
<?php $partners = explode(', ', $partners); ?>
<?php foreach ($partners as $partner) : ?>
<div class="<?php echo($partner) ?>"></div>
<?php endforeach; ?>

Print the specific values from the array

I get the result from my database i this type of array format.Now i want to print the question,answer and category name from the array what I do?
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data->title;?>">
I tried these cod but not get the answer.In $var i get the all the array value
Things to consider:-
1.Your sub-array is again an array so you need to use foreach() on sub-array too. (So basically two foreach())
2.You need to close divs as well as foreach() loops too.
So code need to be like below:-
<?php
foreach($var as $data){
foreach($data['data'] as $dat){
?>
<div class="faqHeader"> <?php echo $dat['category_name'];?>
<div class="panel-group" id="<?php echo $dat['questions'];?>"><?php echo $dat['questions'];?></div>
<div class="panel-group" id="<?php echo $dat['answer'];?>"><?php echo $dat['answer'];?></div>
</div>
<?php } }?>
you can use two loops to simplify your task:-
foreach($var as $index=>data){
echo $data['name']; // this will be your category name
foreach($data as $questionIndex=>$questionData){
echo $questionData['question'];
echo $questionData['answer'];
}
}
Since your array contains multiple data and data contains multiple values itself, you need two foreaches here:
foreach($var as $item) {
foreach($item['data'] as $info) {
var_dump($info);
}
}
Please try this code
<?php
$v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['data'][0]['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data['name'];?>">
<?php
}
?>
You don't have any 'title' index in your array so you may change it to 'name'

PHP Foreach with two or more arrays

How to use Foreach on two or more php arrays?
My arrays are $boardType, $hotelPrice and $hotelName
Solution is to add $index in the other arrays as suffix
<?php foreach ($hotelName as $index => $name):?>
<div>
<p><?php echo $name;?></p>
<p><?php echo $hotelPrice[$index];?></p>
<p><?php echo $boardType[$index];?></p>
</div>
<?php endforeach?>
This should work for you:
(Here I just go through all 3 arrays with array_map() an print them in the structure you want)
<?php
array_map(function($v1, $v2, $v3){
echo "<div>";
echo "<p>$v1</p>";
echo "<p>$v2</p>";
echo "<p>$v3</p>";
echo "</div>";
}, $boardType, $hotelPrice, $hotelName);
?>
Example input/output:
$boardType = [1,2,3];
$hotelPrice = [4,5,6];
$hotelName = [7,8,9];
<div>
<p>1</p>
<p>4</p>
<p>7</p>
</div>
<div>
<p>2</p>
<p>5</p>
<p>8</p>
</div>
<div>
<p>3</p>
<p>6</p>
<p>9</p>
</div>
If all arrays have exactly the same size you could use each to iterate through the other arrays at the same time as $hotelName:
<?php foreach ($hotelName as $index => $name):?>
$price = each($hotelPrice);
$boardType = each($boardType);
<div>
<p><?php echo $name;?></p>
</div>
<?php endforeach?>
However, in that case it would probably being better to have just a single array containing all the data.

Echo array value in different sections

I want to echo a value of an array in a way that the first 4 would echo in a section and the rest (can be 5 or more) in a different section. For example:
<?php $items = $kStore->getItems(); ?>
<div id="section1">
<?php foreach($items as $item) {
if($count <= 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } }?>
</div>
<div id="section2">
<?php foreach($items as $item) {
if($count > 4){
?>
<h1><?php echo $item->getId(); ?></h1>
<?php } } ?>
</div>
I imagine it has to be something 'like that' but dont know how to get the count. Also, I don't want to go through the array twice, I feel it's not the fastest way to do it. Any thoughts? Thanks!
You can use array_slice to offset the start and limit the length of the section of the array you iterate over:
<div id="section1">
<?php foreach(array_slice($items, 0, 4) as $item) { … } ?>
</div>
<div id="section2">
<?php foreach(array_slice($items, 4) as $item) { … } ?>
</div>
Update
If $items is not an array, but merely a non-array object that implements Iterator, you can't use this approach, but you can probably use LimitIterator instead.
<?php
$sectionOneItems = new LimitIterator($items, 0, 4);
$sectionTwoItems = new LimitIterator($items, 4);
?>
<div id="section1">
<?php foreach($sectionOneItems as $item) { … } ?>
</div>
<div id="section2">
<?php foreach($sectionTwoItems as $item) { … } ?>
</div>
If this, too, does not work, then some more introspection of the object being iterated over is required.
i think this function might be useful for you
array_chunk ().http://www.php.net/manual/en/function.array-chunk.php

Looping through a PHP array

I have the following PHP array structure:
$set = array();
$set[] = array('firstname'=>'firstname 1',
'lastname'=>'lastname 1',
"bio"=>array('paragraph 1 of the bio, 'paragraph 2 of the bio','paragraph 3 of the bio'),
);
I then access the array with the following:
<?php $counter = 0;
while ($counter < 1) : //1 for now
$item = $set[$counter]?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php endwhile; ?>
I'm uncertain how I can loop through the "bio" part of the array and echo each paragraph.
So as a final output, I should have two h1s (first and last name) and three paragraphs (the bio).
How can I go about doing this?
Use foreach loop
foreach($item['bio'] as $listitem) {
echo $listitem;
}
You don't need to use a manual counter, you can use foreach. It's generally the easiest way and prevents off-by-one errors.
Then you need a second inner loop to loop through the bio.
<?php foreach ($set as $item): ?>
<h1><?php echo $item['firstname'] ?></h1>
<h1><?php echo $item['lastname'] ?></h1>
<?php foreach ($item['bio'] as $bio): ?>
<p><?php echo $bio; ?></p>
<?php endforeach; ?>
<?php endforeach; ?>
On a related note; you probably want to look into escaping your output.
Add into the while loop also this:
<?php foreach ($item['bio'] as $paragraph): ?>
<p><?php echo $paragraph; ?></p>
<?php endforeach; ?>
Note that used coding style is not optimal.
Try:
foreach($set as $listitem) {
if(is_array($listitem)) {
foreach($listitem as $v) //as $set['bio'] is an array
echo '<h1>' .$v . '</h1>';
} else
echo '<p>'.$listitem.'</p>';
}

Categories