【发布时间】:2013-08-31 13:27:33
【问题描述】:
我正在为 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>");
});
});
【问题讨论】:
-
这不是 jquery 问题,似乎是 php 问题。建议调整标签
-
您认为哪些数组是“额外的”和“不必要的”?最外面的数组是
$pop_posts本身;下一层由array($cat,$myposts)产生;$myposts被构建为一个帖子列表,每个帖子都是一个哈希($myposts[] = array('title'=>...);在每个散列中,image键是wp_get_attachment_image_src返回的数组。