0

I'm trying to create JSON feed from one site which i want to decode on another. The problem is there seem to be to many array[0], so it is hard to loop through it and count how many objects there are.

How can i do this encode and decode without getting all these arrays, to make it easier to count the amount of objects and loop through it.

at the moment i'm encoding it like this:

$data = array();
foreach ($posts as $post) {
    $r = str_replace("\n",'', shorten_txt($post->post_content, 500));
    $n = str_replace("\r", '', $r);
    $post_data = array(
    'title' => get_the_title($post->ID),
    'link' => get_permalink($post->ID),
    'image' => catch_that_image(),
    'content' => $n,
    'time' => get_the_date( $d)." ". get_the_time( $d));
     $data[] = (array('item' => $post_data));

}
echo json_encode($data);

This gives this output:

[
    {
        item: {
            title: "Hello world!",
            link: "http://URL/wordpress/?p=1",
            image: "http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png",
            content: "Welcome to WordPress. This is your first post. Edit or delete it,             then start blogging!",
            time: "April 17, 2014 5:32 pm"
        }
    }
]

When i decode this i get this:

Array ( [0] => Array ( [item] => Array( [title] => Hello world! [link] => http://URL/wordpress/?p=1 [image] => http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png [content] => Welcome to WordPress. This is your first post. Edit or delete it, then start blogging! Jeg elsker kage [time] => April 17, 2014 5:32 pm ) ) )

The decode code:

$json_string = 'http://95.85.11.40/wordpress/?page_id=20';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
print_r($obj);
1
  • is echo json_encode($data[0]); ok? Commented May 16, 2014 at 15:41

1 Answer 1

1

If you don't want those array[0] bits, then don't create a 2D array:

$data[] = (array('item' => $post_data));

Should then be:

$data[] = $post_data;

Your current statement read as _add to array $data an array, with 1 key: "item", whereas my version just says: add to $data the value of $post_data.

loping oiver decoded data:

$data = json_decode(file_get_contents($jsonFile), true);
foreach ($data as $idx => $item)
{
    echo 'This is item number ', $idx +1, PHP_EOL;
    print_r($item);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.