Split array into div [duplicate] - php

This question already has answers here:
Break PHP array into 3 columns
(7 answers)
Closed 7 years ago.
I have this array :
$result = array('description1', 'description2', 'description3', 'description4', 'description5'
I want to split this array into divs like this :
$result[0] - $result[1] => put these into a div
$result[2] - $result[3] => put these into a div
$result[4] => put this into a div
My entire structure
$content = get_the_content();
$description = array();
$j=0;
if (preg_match_all('/<div id="description" class="description">([^<]*)<\/div>/', $content, $match)) {
for( $i = 0; $i < count($match[0]); $i = $i+1 ) {
$description[] = $match[0][$i];
}
}
$attachments =& get_children($args);
$arrayMatches = array();
if ($attachments) {
foreach(array_chunk($attachments, 2) as $img) {
echo '<div class="two_cols">';
foreach($img as $attachment) {
foreach($attachment as $attachment_key => $attachment_value) {
$imageID = $attachment->ID;
$imageTitle = $attachment->post_title;
$imagearray = wp_get_attachment_image_src($attachment_value, $size, false);
$imageAlt = get_post_meta($imageID, '_wp_attachment_image_alt', true);
$imageURI = $imagearray[0]; // 0 is the URI
$imageWidth = $imagearray[1]; // 1 is the width
$imageHeight = $imagearray[2]; // 2 is the height
?>
<div class="col_1_2">
<!-- A picure Here -->
<?php $arrayMatches[] = $match[0][$j]; ?>
</div>
<?php
break;
}
$j++;
}
$arrayMatches = array_chunk($arrayMatches, 2);
echo "<div>";
foreach($arrayMatches as $v) {
echo implode($v);
}
echo "</div>";
echo '</div>';
}
}

This should work for you:
Just chunk your array with array_chunk(). And then you can simply loop through your array, output it into a div and implode() the elements.
<?php
$result = array('description1', 'description2', 'description3', 'description4', 'description5');
$result = array_chunk($result, 2);
foreach($result as $v) {
echo "<div>" . implode(" ", $v) . "</div>";
}
?>
output:
<div>description1 description2</div>
<div>description3 description4</div>
<div>description5</div>
EDIT:
As from your updated array structure just grab all values first like this:
$result = [];
$arr = array(['description1'], ['description2'], 'description3', 'description4', 'description5'); //example
array_walk_recursive($arr, function($v, $k)use(&$result){
$result[] = $v;
});
$result = array_chunk($result, 2);

Can you not just echo them in divs:
<div>
<?php echo $result[0] . "-" . $result[1]; ?>
</div>
<div>
<?php echo $result[2] . "-" . $result[3]; ?>
</div>
<div>
<?php echo $result[4]; ?>
</div>

You just need to control whether you are in the last 2 positions or not.
echo '<div>';
for ($i=0;$i<count($result);$i=$i+2) {
if ($i+1 >= count($result)) {
echo $result[$i];
} else {
echo $result[$i].$result[$i+1];
echo '</div><div>';
}
}
echo '</div>;

Related

Use Array in PHP [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
I'm fairly new to PHP and I'm trying to make an array and use the elements of that array in my PHP Website by using $_GET.
I get my array like this:
<?php $values = explode(",", $_GET["id"]); ?>
And these here work fine:
<img src="<?php echo $values[0]; ?>">
<img src="<?php echo $values[1]; ?>">
This one however doesn't work
$newsSource = array(
array(
"title" => "COMPANY",
"url" => $values[2]
)
);
...
function getFeed($url){
...
Can I not assign an array value like that?
URL Example
https://DOMAIN/PHPFILE.php?id=IMAGE.jpg,IMAGE.png,RSS_FEED_WEBSITE,one
Full Code Here:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php $values = explode(",", $_GET["id"]);
// 0 = Logo
// 1 = News Logo
// 2 = RSS Feed
// 3 = Page
?>
<div class="container">
<div class="logo">
<img src="<?php echo $values[0]; ?>">
</div>
<div class="logo">
<img src="<?php echo $values[1]; ?>">
</div>
<?php
function getContent() {
$file = "./feed-cache.txt";
$current_time = time();
$file_time = filemtime($file);
if(file_exists($file) && ($current_time < $file_time)) {
return file_get_contents($file);
}
else {
$content = getFreshContent();
file_put_contents($file, $content);
return $content;
}
}
function getFreshContent() {
$html = "";
$newsSource = array(
array(
"title" => "COMPANY",
"url" => $values[2]
)
);
function getFeed($url){
$html = "";
$rss = simplexml_load_file($url);
$count = 0;
$page = $values[3] ?? 'one';
if ($page == 'two') {
$counter = 2;
} else if ($page == 'three') {
$counter = 4;
} else {
$counter = 0;
}
$itemcount = count($rss->channel->item);
for ($i = $counter; $i <= $counter+1; $i++) {
$curr_item = ($rss->channel->item[$i]);
// split description from img and text
$content = ($curr_item->description);
preg_match('/(<img[^>]+>)/i', $content, $matches);
$item->image = $matches[0];
$item->description = str_replace($matches[0],"",$content);
$html .= '<div class="entry"><h3>'.htmlspecialchars($curr_item->title).'</h3>';
$html .= '<div class="entry-image">'.($item->image).'</div>';
$html .= '<div class="entry-text">'.($item->description).'</div>';
$html .= '</div>';
}
return $html;
}
foreach($newsSource as $source) {
//$html .= '<h2>'.$source["title"].'</h2>';
$html .= getFeed($source["url"]);
}
return $html;
}
print getContent();
?>
</div>
</body>
</html>
After updating the problem, I found the problem.
In methods, variables need to be passed in!
function getFreshContent($values) {
// ...

PHP - How to wrap every 2 items of a 'for' loop within a div

I'm looking for a way to wrap every too items of this very basic for loop within a div :
<?php
for( $i=1; $i<=50; $i++ )
{
echo "<div><a href='item-".$i."'>".$i."</a></div>";
}
?>
This produces the following :
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
The output i need would be :
<div>1 2</div>
<div>3 4</div>
Thanks
Easiest way i can think of is by doing this. This also works if you have a resultset from a database, or an array of item objects, just replace the range() function with the array.
<?php
foreach (array_chunk(range(1, 50), 2) as $chunk) {
echo "<div>";
foreach ($chunk as $itemId) {
echo "<a href='item-" . $itemId . "'>" . $itemId . "</a>";
}
echo "</div>" . PHP_EOL;
}
Use modulo operator
code:
<?php
$chunks = 2;
$display = true;
for( $i=1; $i<=6; $i++ )
{
if ($display && ($i % $chunks || $chunks === 1)) {
echo "<div>";
$display = false;
$last = true;
}
echo "<a href='item-".$i."'>".$i."</a>";
if (!($i % $chunks)) {
echo "</div>" . PHP_EOL;
$display = true;
$last = false;
}
}
if ($last) {
echo "</div>" . PHP_EOL;
}
generates:
<div><a href='item-1'>1</a><a href='item-2'>2</a></div>
<div><a href='item-3'>3</a><a href='item-4'>4</a></div>
<div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and with:
$chunks = 3;
you will get:
<div><a href='item-1'>1</a><div><a href='item-2'>2</a><a href='item-3'>3</a></div>
<div><a href='item-4'>4</a><div><a href='item-5'>5</a><a href='item-6'>6</a></div>
and so one.

Add links within a foreach loop

I have a loop which displays the tags, I'd like to add an anchor link to those tags. My code is as follows:
<?php $brands = get_the_tags(); ?>
<p class="brand-tags">
<?php
$count = 0;
foreach ($brands as $brand) {
// echo sizeof($brands);
if ($count < sizeof($brands)-1) {
echo $brand->name.', ';
$count += 1;
}
else {
echo $brand->name;
}
}
?>
</p>
Try this
$brands = get_the_tags();
$links = array();
foreach($brands as $_brand){
$links[] = ''.$_brand->name.'';
}
echo join(', ', $links);
I assume you want to add link to brand name? Here is the code for that:
<?php $brands = get_the_tags(); ?>
<p class="brand-tags"><?php
$count = 0;
foreach ($brands as $brand) {
// echo sizeof($brands);
if ($count < sizeof($brands)-1) {
echo ''.$brand->name.' ';
$count += 1;
} else {
echo ''.$brand->name.' ';
}
} ?></p>

create div from each item in tags column

My tags column is like this:
first row: sky - earth - sea
second row: iron - silver - gold
third row: apple - fruit - food
...and so on
Want to create a div from each item, like this:
<div class='tagdown'>sky</div>
<div class='tagdown'>earth</div>
$st = $db->query("select tags from posts");
$arr = array();
$items = "";
while ($row = $st->fetch()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $item) {
$items .= "<div class='tagdown'>" . $item . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Another Try:
for ($i = 0; $i < count($arr); ++$i) {
$items .= "<div class='tagdown'>" . $arr[$i] . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Any help?
Dont push and again traverse your array. just print out data in while loop. Try following code:
$items = "";
while ($row = $st->fetch()) {
$arr = explode(' - ', $row['tags']);
$items .= "<div class='tagdown'>".implode("</div>\n<div class='tagdown'>",$arr)."</div>\n";
}
echo $items;
Try like shown below
Example :
<?php
$items = "";
$str = "sky-earth-sea";
$arr = explode("-", $str);
$count = count($arr);
for($i = 0; $i < $count; $i++) {
$items .= "<div class='tagdown'>".$arr[$i]."</div></br>";
}
echo $items;
?>
explode() returns an array and you are pushing an array into an other array
its making 1 2D array you can check thar using print_r($arr);
use this
while ($row = $st->fetch()) {
$tag=explode('-', $row['tags'];
foreach($tag as $t){
array_push($arr,$t ));
}
}
You can also use fetch associative if using mysqli_connect
while ($row = $result->fetch_assoc()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $a) {
foreach($a as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;
-------------- OR -------------
$arr = array();
$items = "";
while ($row = $result->fetch_assoc()) {
$tag = explode(' - ', $row['tags']);
foreach($tag as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;

start end div after some elements php

I cannot solve problem with starting ending divs after couple of elements from array.
What i want to get is something like that:
<div>
element1
element2
element3
element4
</div>
<div>
element5
element6
element7
element8
</div>
<div>
element9
element10
</div>
Here is my php code:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 1;
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 OR $count == 1){
echo '<div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
Try something like this
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$perRow = 4;
$count = 0;
echo '<div>';
foreach ($array as $arr){
// here div needs to start, use 4 elements from array and close
if($count % $perRow == 0 && $count!=0){
echo '</div><div>';
}
echo $arr . '<br>';
// here should div close
$count++;
}
echo '</div>';
Okay I am not familiar with arrays and maybe something like this would work:
$array = array("element1","element2","element3","element4","element5","element6","element7","element8","element9","element10");
$i=0;
echo '<div>'
if (i<3) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>3 && $i<7) {
echo '$array[$i]';
$i++;
}
echo '</div>';
echo '<div>';
if ($i>7 && $i<10) {
echo '$array[$i]';
$i++;
}
echo '</div>';

Categories