PHP loop through multidimensional JSON array and load data on button click
Basically I am fetching JSON content from php call using some custom API. Arrays are all social posts. The code I'm using at the moment displays them all at once when the page is loaded. I would like to show them 10 or 20 in time, depending on my need, I am using a PHP foreach loop to post data to the page. I would like to get the first 10 indices (from [0]
to [10]
) and configure the button to load the next indices [11], [12], [13]...
, let 10 be in time (from [11]
to [20]
, from [21]
to [30]
) on each click. Is it possible?
The JSON content looks like this:
Array
(
[comments] => Array
(
[0] => Array
(
[type] => instagram
[author] => Rick B.
[message] => ππΏ #follow4follow #followme
[authorImage] => https://image.load.here/image.jpg
)
[1] => Array
(
[type] => twitter
[author] => John Tesla
[message] => Welcome to the Fine Living
[authorImage] => https://image.load.here/image.jpg
)
[2] => Array
(
[type] => facebook
[author] => Rob Roy
[message] => Buscando el perfect sunset!
[authorImage] => https://image.load.here/image.jpg
)
[...]
[180] => Array
(
[type] => vine
[author] => Joe Fox
[message] => Bom dia insΓ΄nia! #bomdia
[authorImage] => https://image.load.here/image.jpg
)
)
)
This is the (semplified) code I am using:
<!-- load content loop -->
<?php if(count($comments) > 0): ?>
<?php
$counter = 0;
foreach($comments as $comment): ?>
<?php
$type = $comment['type'];
$author = $comment['author'];
$message = $comment['message'];
$avatar = $comment['authorImage'];
$counter++;
?>
<!-- write content -->
<?php
// need to repeat this block of code eg. 10 times
// and not eg: 180 (is the actual number of indexes [0], [1], [2] in my JSON array.
echo '<div class="social ' . $type . '">
<p class="icon"><img src="'.$type.'".jpg"/></p>
<p class="avatar">' . $avatar . '</p>
<p class="author">Posted by ' . $author . '</p>
<p class="message">' . $message . '</p>
</div>';
?>
<?php endforeach; ?>
<?php else: ?>
<h2>There are no comments yet</h2>
<?php endif; ?>
source to share
<?php
function doMyStuff()
{
// Doing all your other stuff in here..
$currentIndex = 30;
getData($currentIndex);
}
function getData(currentIndex) {
$maxIndex = currentIndex + 10;
for($x = $currentIndex; $x < maxIndex; $x++) {
echo '<div class="'. $comment['content{$x}'] .'"><p>Content..'..'</p></div>';
}
}
This may or may not be what you are looking for, but basically ... pass the getData function with the current array index, say 30 - getData (30); then the function will display the next 10 content based on the current index, and the maximum index is 10 more than the current one.
['content {$ x}'] is an easy way to directly insert a variable / object into a string.
source to share