PHP цикл по многомерному массиву JSON и загрузка данных по нажатию кнопки

По сути, я получаю JSON-контент из php-вызова, используя какой-то пользовательский API. Массивы — это все социальные посты. Код, который я использую в данный момент, отображает их все сразу при загрузке страницы. Я хотел бы показать их 10 или 20 раз, в зависимости от моих потребностей, я использую цикл foreach PHP, чтобы поместить данные на страницу. Я хотел бы получить первые 10 индексов (из [0] в [10]) и установите кнопку для загрузки следующих индексов [11], [12], [13]...скажем, 10 раз (от [11] в [20], от [21] в [30] ) при каждом нажатии. Это возможно?

Содержимое JSON выглядит так:

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

Это (упрощенный) код, который я использую:

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

3

Решение

<?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>';
}

}

Это может или не может быть тем, что вы ищете, но в основном … передайте функцию getData с текущим индексом массива, скажем, 30 — getData (30); затем функция выведет на экран следующие 10 содержимого на основе текущего индекса, а максимальный индекс будет на 10 больше текущего.

[‘content {$ x}’] — это аккуратный маленький способ прямой вставки переменной / объекта в строку.

1

Другие решения

Других решений пока нет …