Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Logan R
22,989 PointsOffsetting Json
Hey guys, I need a way to offset JSON.
Say I have posts.json:
{
"posts": [
{
"id": "4"
},
{
"id": "3"
},
{
"id": "2"
}
]
}
I want it so PHP will skip the { id 4 } and start with id 3. I tried array_shift() but it didn't work :/
If anyone could help, that would be great! I am trying to do pagination with static JSON soo yeah.
<?PHP
$json_file = file_get_contents('data/posts.json');
$json = json_decode($json_file, true);
define('page', '2');
$page = $json["posts"][0]["id"];
//exit;
?>
<?PHP include 'inc/header.php'; ?>
<section class="main">
<?PHP
$x=1;
foreach($json["posts"] as $json) {
if($x > page){
break;
}
echo '
$json["id"]
';
$x=$x+1;
}
?>
2 Answers

Logan R
22,989 PointsI've solved the problem! I will post the code once I finish everything up :)
Edit - I feel super smart for this code, lol. I also had to do it all without help, so it's even better :D
<?PHP
if(isset($_REQUEST['page'])){
$page = intval($_REQUEST['page']);
if($page < 1){
$page = 1;
}
}else{
$page = 1;
}
$json_file = file_get_contents('data/posts.json');
$json = json_decode($json_file, true);
define('page', '4');
$pages = $json["posts"][0]["id"];
$page_offset = $page*page-page;
?>
<?PHP include 'inc/header.php'; ?>
<section class="main">
<?PHP
$x=$page_offset;
$json = $json["posts"];
for ($z=0; $z<page; $z++, $x++) {
if($z > page){
break;
}
if($x == $pages){
break;
}
echo '
<div class="post_block">
<div class="feature">
<img src="'.$json["$x"]["img"].'">
</div>
</div>
';
}
?>
{
"posts": [
{
"id": "5",
"img": "img/forest1.jpg"
},
{
"id": "4",
"img": "img/forest1.jpg"
},
{
"id": "3",
"img": "img/forest1.jpg"
},
{
"id": "2",
"img": "img/forest1.jpg"
},
{
"id": "1",
"img": "img/forest1.jpg"
}
]
}
Mike Baxter
4,442 PointsI'm not entirely sure, but here are a couple thoughts.
Can't you just use numbers as your JSON id values instead of using strings? I guess it's trivial to do intval() on the string, but why do it if it's not necessary?
My memory's a little fuzzy, but I don't think you'll want that comma at the end of your JSON array. (So do a logic check in the for loop to avoid inserting the comma at the end of the value the last time through the loop.)

Logan R
22,989 Points- There was a lot more to the file and I edited on the fly, I changed it in the official post.