我正在为 json_encode 的输出而苦苦挣扎。我试图通过将所有内容存储在一个每天更新一次的 json 文件中并在需要时调用它来加速我们的大型下拉导航菜单。
我正在使用 json_encode 生成 json,但它似乎将所有内容循环到额外的、不必要的数组中,我不知道如何防止这种情况发生。
我什至尝试过摆弄 str_replace 但未能成功生成有效的 json(尽管显然这在任何情况下都不是真正的长期解决方案)。我还试图弄清楚进入嵌套数组需要什么“每个”组合,但没有找到正确的组合。
下面是我最终得到的 json(我减少了条目数量以使其更容易查看,格式相同......只是在电影、游戏等每个项目中都有更多项目)。
[
[
"Film",
[
{
"title": "13 Awkward Moments That Must Have Happened After The End Of Famous Movies",
"link": "http:\/\/whatculture.com\/film\/13-awkward-moments-that-must-have-happened-after-the-end-of-famous-movies.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/HP-100x60.jpg",
100,
60,
true
]
}
]
],
[
"TV",
[
{
"title": "10 Awesome TV Twists You Never Saw Coming",
"link": "http:\/\/whatculture.com\/tv\/10-awesome-tv-twists-you-never-saw-coming.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/lost-locke-100x60.jpg",
100,
60,
true
]
}
]
],
[
"Gaming",
[
{
"title": "WWE 2K14: Every Possible Classic Match",
"link": "http:\/\/whatculture.com\/gaming\/wwe-2k14-every-possible-classic-match.php",
"image": [
"http:\/\/cdn3.whatculture.com\/wp-content\/uploads\/2013\/08\/444-100x60.jpg",
100,
60,
true
]
}
]
]
]
这是我用来生成上述代码的脚本:
为了完整起见,我已经包含了所有内容。以下很多内容只是用于拉回我的相关数据的 Wordpress 查询:
$cats = array("Film","TV","Gaming","Sport","Music");
function filter_where($where = '') {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-3 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
foreach($cats as $cat) {
$the_query = array(
'numberposts' => 5,
'category_name' => $cat,
'meta_key' => "visitcount",
'orderby' => "meta_value_num",
'suppress_filters' => false );
$special_query_results = get_posts($the_query);
foreach( $special_query_results as $post ) {
setup_postdata($post);
$myposts[] = array('title'=> html_entity_decode(get_the_title()),'link'=>get_permalink(get_the_ID()),'image'=>wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'smallthumb' ));
}
$pop_posts[] = array($cat,$myposts);
unset($myposts);
} // foreach cats as cat1000
wp_reset_postdata();
remove_filter('posts_where', 'filter_where');
$json_pop = json_encode($pop_posts,JSON_PRETTY_PRINT);
当用户将鼠标悬停在导航项上时,这就是我用来将其拉回的方法:
$.getJSON('http://whatculture.com/data/wc6.json', function(popular) {
$.each(popular.Sport, function() {
$('.popularMenu').append("<li><a href="+this.link+"><img src="+this.image[0]+" />"+this.title+"</a></li>");
});
});