Spread foreach() results over two columns of a table - php

I'm trying to spread the results of a foreach() loop over two columns of a table (sorry can't post images as this is my first post to stack overflow). I can see where I'm going wrong but haven't a clue how to correct it. I though maybe a next() instead of repeating the foreach() but can't seem to get that to work. Any help would be greatly appreciated.
I need this:
result1 result2
result3 result4
but I'm getting this:
result1 result1
result2 result2
<table>
<?php
foreach ($tags as $tag) {
echo '<tr><td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td>';
next ($tag);
echo '<td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag- >tag).'_id">'.$tag->tag.'</label></td></tr>';
}
?>
</table>

You should try to simplify your code when debugging. This would help you isolate the problem and make it easier for communities like StaceOverflow to help you. It looks like this:
<?php
// some fixtures for us to work with
$tags = array('foo', 'bar', 'lolo', );
?>
<pre>
<?php
// your actual issue
foreach ($tags as $tag) {
var_dump( $tag );
next( $tag );
var_dump( $tag );
}
?>
</pre>
You'd see this (wrong) output, which is pretty much the problem you're talking about isn't it ? ;)
string(3) "foo"
string(3) "foo"
string(3) "bar"
string(3) "bar"
string(4) "lolo"
string(4) "lolo"
The signature of next() is:
mixed next ( array &$array )
Which means that it returns a value of any type from an array which is passed by reference. In your case it applies like this:
$tag = next( $tags );
But what happens if you call next() on the last item ?
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
You should break the for loop if next returns false, e.g.:
$tag = next( $tags );
if ( $tag === false ) break;
More elaborated example:
<?php
class Tag {
public $tag;
public function __construct( $tag ) {
$this->tag = $tag;
}
}
$tags = array( );
foreach ( array('foo', 'bar', 'lolo', ) as $word) {
$tags[] = new Tag( $word );
}
$search = array( 'bar', 'the' );
?>
<pre>
<?php
foreach ($tags as $tag) {
var_dump( $tag );
$tag = next( $tags );
if ( $tag === false ) {
break;
}
var_dump( $tag );
}
?>
</pre>
Will output just fine:
object(Tag)#1 (1) {
["tag"]=>
string(3) "foo"
}
object(Tag)#3 (1) {
["tag"]=>
string(4) "lolo"
}
object(Tag)#2 (1) {
["tag"]=>
string(3) "bar"
}
Here's the solution applied to your code (tested/working):
<table>
<?php
foreach ($tags as $tag) {
echo '<tr><td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td>';
$tag = next ($tags);
if ( $tag === false ) {
break;
}
echo '<td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td></tr>';
}
?>
</table>
The php manual for next also includes an important note:
Note: You won't be able to distinguish the end of an array from a
boolean FALSE element. To properly traverse an array which may contain
FALSE elements, see the each() function.

If both columns are exactly the same, or especially if you need more than 2, I recommend this condensed approach (I haven't done a lot of testing on this):
<table>
<tr>
<?php
$count = 0;
$columnCount = 2;
foreach ($interests as $interest) {
if($count++ % $columnCount == 0){
echo "</tr><tr>";
}
echo "<td>$interest->name</td>";
}
while($count++ % $columnCount != 0){
echo "<td> </td>";
}
?>
</tr>
</table>
It will not handle an empty array correctly, so you should add your own code to handle that. You can change columnCount to whatever you want, if you want more than 2 columns.

Related

concatinating two array elements with a string within a foreach loop

I am trying to combine two array elements with the string "OR" and create one string of elements.
The array looks like this:
$myarray = array(2282396,1801345)
This is the code i have used.
$bool = ' OR ';
foreach($myarray as $element){
echo $element .= $bool;
}
I trying to get this output after looping using a foreach loop.
2282396 OR 1801345
However, the output i get looks like this:
2282396 OR 1801345 OR
How do i get rid of the 'OR' after the second element? Thanks in advance
You have to check if you're in the first/last iteration or not.
$first = true;
$bool = ' OR ';
foreach ($myarray as $element) {
if (!$first) {
echo $bool;
}
echo $element;
$first = false;
}
If your array is indexed by numeric indexes 0-x, you an use
$bool = ' OR ';
foreach ($myarray as $key => $element) {
if ($key > 0) {
echo $bool;
}
echo $element;
}
Use implode as:
echo implode(" OR ", $myarray);
Documentation implode
Live example: 3v4l

Get array php bigtee

I am a stuck with Bigtree.
For my website I need to know a pageID, you can do that using a function.
$nav = $cms->getNavId($path, $previewing = false);
But this is what I get back
string(2) "15" array(0) { } string(0) ""
how can I catch the number (in this case 15)
If I do it this way
$nav = $cms->getNavId($path, $previewing = false);
foreach ($nav as $key) {
echo $key;
}
Then I get this output
15Array
So your loop looks like its doing what you want. If you replaced the echo in the loop with a var_dump it would be more clear.
So to grab the 15; do this:
$nav = $cms->getNavId($path, $previewing = false);
foreach ($nav as $key) {
if( is_numeric($key) ){
$navID = $key;
}
}
var_dump($navID);

Getting Value from array

To get the value from var_dump:
mymeta_url_group =>
0 => string(39) "a:1:{s:10:"mymeta_url";s:8:"You rock";}"
1 => string(40) "a:1:{s:10:"mymeta_url";s:9:"Yeah Sure";}"
I have used:
$urls= get_post_meta( get_the_ID(), 'mymeta_url_group', false );
foreach ( $urls as $url)
{
echo $url["mymeta_url"];
// You Rock
//Yeah Sure
}
Now since I have added repeater and sorter option in backend new var dump shows:
mymeta_url_group =>
0 => string(102) "a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:8:"You rock";s:11:"cmb-field-1";s:11:"Nope Maybe ";}}"
1 => string(100) "a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:9:"Yeah Sure";s:11:"cmb-field-1";s:9:"Won't you";}}"
Now How can I get Values "You rock" "Nope Maybe ""Yeah Sure""Won't you" extending my previous solution.
PS if I do var_dump($url["mymeta_url"]);
The output is
Arrayarray(2) { ["cmb-field-0"]=> string(8) "You rock" ["cmb-field-1"]=> string(11) "Nope Maybe " } Arrayarray(2) { ["cmb-field-0"]=> string(9) "Yeah Sure" ["cmb-field-1"]=> string(9) "Won't you" }
I don't know what get_post_meta() is supposed to do, but maybe this will give you some ideas:
<?php
/* Setting up data */
$data = array (
'a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:8:"You rock";s:11:"cmb-field-1";s:11:"Nope Maybe ";}}',
'a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:9:"Yeah Sure";s:11:"cmb-field-1";s:9:"Won\'t you";}}'
);
$urls = array();
foreach ($data as $s) {
$urls[] = unserialize ($s);
}
/* Retrieving data */
foreach ($urls as $url) {
foreach ($url['mymeta_url'] as $u) {
echo "$u, ";
}
echo "\n";
}
Here's what I came up with:
foreach($array as $array2) { //If it doesn't work change $array to $array['mymeta_url_group']
$array2 = unserialize($array2);
foreach($array2['mymeta_url'] as $line) {
echo $line; //$line is the sentance you're looking for
}
}
I'm not sure if will work since I had to reconstruct the array from the var_dump() output.

Check to see if specific text is within an array

I need to check if any specific text is within an array, so basically a stristr within an array. Currently I perform an in_array function but it will not pick it up is the text is only part of the array value;
e.g Search for "man" in the array("Manchester United","Liverpool", "Arsenal") would currently return nothing, but I need it to return Manchester united etc..
Hope someone can help
<?php
$teams = array("Manchester United", "Liverpool", "Arsenal");
$term = "man";
foreach ($teams as $team) {
if (stripos($team, $term) === false) {
continue;
}
echo "Found match: $team\n";
}
?>
Or you could get fancy and use array_filter:
<?php
$teams = array("Manchester United", "Liverpool", "Arsenal");
$term = "man";
$results = array_filter($teams, function ($elt) use ($term) {
return stripos($elt, $term) !== false;
});
?>
How about something like this:
function find($needle, array $haystack) {
$matches = array();
foreach($haystack as $value) {
if(stristr($value, $needle) !== false) {
$matches[] = $value;
}
}
return $matches;
}
$haystack = array("Manchester United", "Liverpool", "Arsenal");
print_r(find('man', $haystack));
Output:
Array
(
[0] => Manchester United
)
Try something like this:
$items = array("Manchester United","Liverpool", "Arsenal");
$results = array();
$searchTerm = 'man';
foreach($items as $item) {
if (stripos($item, $searchTerm) !== false) {
$results[] = $item;
}
}

foreach array displaying result

I have been looking at this code etc for so long that I am now confusing myself - not good
I have foreach of
foreach($sort_order as $sort)
{
echo '<pre>';
var_dump($sort['sorder']);
echo '</pre>';
}
That gives me a result of:
string(2) "20"
string(2) "10"
How can I return this so I can do value="<?php echo $someValue; ?>"
Assuming that 'sorder' is a key in your array I would try the following:
foreach($sort_order as $key => $sort) {
echo '<pre>';
if($key == "sorder") {
echo $sort[$key];
}
echo '</pre>';
}
It looks like you're only displaying they key. I'm assuming your array is of type associative.
To traverse associative arrays in PHP, follow this:
foreach($array as $key => $value)
{
echo "[" . $key . "]" . " = " . $value . "<br />;
}
I'm not sure what are you trying to do but...
<?php
$val = array();
foreach($sort_order as $sort) {
$val[] = $sort['sorder'];
}
?>
<p>value = <?php echo $val[0]; ?></p>
<p>value = <?php echo $val[1]; ?></p>

Categories