dongzuozhu66776 2014-05-16 15:36
浏览 57
已采纳

JSON数组以几个Array开头

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("
",'', shorten_txt($post->post_content, 500));
    $n = str_replace("", '', $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条回答 默认 最新

  • douyiqi9640 2014-05-16 15:42
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法