我正在尝试从一个网站创建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);
答案 0 :(得分:1)
如果您不想要那些array[0]
位,那么就不要创建2D数组:
$data[] = (array('item' => $post_data));
应该是:
$data[] = $post_data;
您当前的语句读作数组$data
为_add,其中包含1个键:" item" ,而我的版本只是说:添加到$data
<{1}} 的价值{。}}。
loping oiver解码数据:
$post_data