JSON数组以几个array开头


JSON array start with several Array

我试图从一个网站创建JSON feed,我想在另一个网站上解码。问题是似乎有很多数组[0],所以很难遍历它并计算有多少对象。

我如何在不获得所有这些数组的情况下进行编码和解码,以使其更容易计数对象的数量并循环遍历它。

现在我是这样编码的:

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

输出如下:

[
    {
        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"
        }
    }
]

当我解码这个我得到这个:

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

解码码:

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

如果你不想要这些array[0]位,那么就不要创建2D数组:

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

应该是:

$data[] = $post_data;

您当前的语句读取为_add到数组$data一个数组,具有1键:"item",而我的版本只是说:添加到$data$post_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);
}