Use Array in PHP [duplicate] - php

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) {
// ...

Related

stuck with simple php looping logic

I have an array which can have any no. of elements in it. Now i want to loop this array and create design such that each li can have 15 elements inside it , next set of li will be created based of multiples of 15's elements.
Now my array has exact 15 elements and the code i am trying creating 2 li , which it should create only 1 li.
May be my logic is too bad or I am missing anything.
Here is my code:-
<?php $result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); ?>
<div class="slide">
<?php $design = '<ul class="slides"><li><div class="MainSlider">';
foreach($result as $key=>$row)
{
$design .= '<div class="MainSliderPic">'.$key.'</div>';
if(($key+1)% 15 == 0){
$design .= '</div></li><li><div class="MainSlider">';
}
if(count($result) == $key+1){
$design .= '</div></li></ul>';
}
}
echo $design;
?>
</div>
You can use array_chunk for to achieve it:
$result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$chunks = array_chunk($result, 15);
foreach ($chunks as $chunk) {
echo '<ul><li>';
echo implode('</li><li>', $chunk);
echo '</li></ul>';
}
Don't mix opening and closing of tags in your code. Do it separately where it belongs, e.g.
$design = '<ul class="slides">';
$n = 0;
foreach($result as $key=>$row) {
if ($n == 0)
$design .= '<li><div class="MainSlider">';
$design .= '<div class="MainSliderPic">' . $key . '</div>';
++$n;
if ($n == 15) {
$design .= '</div></li>';
$n = 0;
}
}
$design .= '</ul>';
echo $design;
Try following code:
<?php $result = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15); ?>
<div class="slide">
<?php $design = '<ul class="slides"><li><div class="MainSlider">';
foreach($result as $key=>$row)
{
$design .= '<div class="MainSliderPic">'.$key.'</div>';
if((($key+1)% 15 == 0) && (count($result) != ($key+1))){
$design .= '</div></li><li><div class="MainSlider">';
}
if(count($result) == $key+1){
$design .= '</div></li></ul>';
}
}
echo $design;
?>
</div>

HTML Simple DOM result to HTML table

I have a problem with HTML simple DOM. I need get results from parse to HTML table with two columns.
I have following code:
<table>
<?php
$html = '<td class="colEvent">
<span class="zapas" data-m="2423050">Wawrinka-A.Murray</span>
<span class="datum">03.06. 15:05</span></td>';
$dat = array();
foreach($html->find('span[class=datum]') as $date) {
$dat[] = $date->innertext;
$a = strip_tags($date->innertext, '<br>');
echo "<tr><td>$a</td>";
}
$zap = array();
foreach($html->find('span[class=zapas]') as $match) {
$zap[] = $match->innertext;
$c = strip_tags($match->innertext, '<br>');
echo "<td>$c</td></tr>";
}
?>
</table>
Try this:
<table>
<?php
$html = '<td class="colEvent">
<span class="zapas" data-m="2423050">Wawrinka-A.Murray</span>
<span class="datum">03.06. 15:05</span></td>';
$dat = array(); $zap = array();
for($i=0; $i<count($html->find('span[class=datum]')); $i++){
$dat[] = $html->find('span[class=datum]')[$i]->innertext;
$a = strip_tags($html->find('span[class=datum]')[$i]->innertext, '<br>');
echo "<tr><td>".$a."</td>";
$zap[] = $html->find('span[class=zapas]')[$i]->innertext;
$c = strip_tags($html->find('span[class=zapas]')[$i]->innertext, '<br>');
echo "<td>".$c."</td></tr>";
}
?>
</table>

Trying to Reverse Order of Images in PHP

I'm trying to reverse the order of images that are displayed. I'm a PHP noob and I'm not sure how to do it. I guess I need to reverse the order of foreach that is displayed, but I'm not entirely sure how to do that.
<div class="yacht-view-right">
<?php
if (count($tpl['gallery_arr']) > 0)
{
$is_open = false;
foreach ($tpl['gallery_arr'] as $k => $v)
{
if ($k == 0)
{
$size = getimagesize(BASE_PATH . $v['medium_path']);
?>
<p><?php print_r(array_keys($v));
print_r(array_VALUES($v));
echo (count($tpl['gallery_arr']))
?></p>
<div class="yacht-view-pic" id="yacht-view-pic" style="width:<?php echo $size[0]; ?>px; height: <?php echo $size[1]; ?>px;">
<img id="yacht-view-medium-pic" src="<?php echo BASE_PATH . $v['medium_path']; ?>" alt="<?php echo htmlspecialchars(stripslashes($v['title'])); ?>"/> </a>
</div>
<?php
}h
$is_open = true;
?>
<div class="yacht-view-img">
<a href="<?php echo BASE_PATH . $v['large_path']; ?>" data-lightbox="yachts">
<img src="<?php echo BASE_PATH . $v['small_path']; ?>" alt="<?php echo htmlspecialchars(stripslashes($v['title'])); ?>" />
</a>
</div>
<?php
/*if ($k > 0 && ($k + 1) % 4 === 0)
{
$is_open = false;
?><div class="clear_left"></div><?php
}*/
}
if ($is_open)
{
?>
<div class="clear_left"></div>
<?php
}
} else {
}
?>
You can simply use array_reverse() before starting your foreach iteration:
$is_open = false;
$tpl['gallery_arr'] = array_reverse( $tpl['gallery_arr'], true );
foreach ($tpl['gallery_arr'] as $k => $v)
You could simply reverse the order of the array using array_reverse before iterating through it with foreach:
foreach ( array_reverse( $tpl['gallery_arr'] ) as $k => $v)
or you could iterate in reverse using a counter (which may have slightly better performance, if the array is large):
$gallery = $tpl['gallery_arr'];
for($i = $first = count($gallery) - 1; $i >= 0; $i-- ) {
$v = $gallery[$i];
if ( $k == $first ) {
...
}
So it looks like you could use the array_reverse() function
$tpl['gallery_arr'] = array_reverse( $tpl['gallery_arr'], true );
foreach ($tpl['gallery_arr'] as $k => $v){
...
}
Or use a regular for loop with inverted parameters.
for($k = count($tpl['gallery_arr']) - 1; $k >= 0; $k--){
$v = $tpl['gallery_arr'][$k];
...
}

Split array into div [duplicate]

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>;

Wordpress: How to split Widget title like Post and title

Hi i am working on wordpress . I want to split my Widget's Title like i did in Post-title(Given below).
<a href="<?php the_permalink(); ?>" rel="bookmark"><?php
global $post;
$str = $post->post_title;
$exp = explode(" ",$str);
echo "<h2>".$exp[0];
echo " <span> ".$exp[1].' '.$exp[2].' '.$exp[3].' '.$exp[4].' '.$exp[5].' '.$exp[6]."</span></h2>";?></a>
Output is:
<h1>This<span> is a title</span></h1>
This will might help you.
global $post;
$arr = explode(' ',$post->post_title);
$j=0;
$str = '';
for($i=0; $i<count($arr); $i++){
$j = $j + 1;
if($j == 1){
$str .= $arr[$i].' <span>';
} else{
$str .= ' '.$arr[$i];
}
}
$str .= '</span>';
echo $str;

Categories