将 foreach 与 Wordpress 一起使用的未定义索引

Undefined index using foreach with Wordpress

提问人:Joe Conlin 提问时间:12/31/2015 最后编辑:Joe Conlin 更新时间:12/31/2015 访问量:260

问:

好吧,我漫长的一天正在赶上我......我正在尝试列出自定义帖子元字段并不断收到通知:未定义的索引:相关标题...数组如下所示:

Array ( [0] => Array ( [0] => Array ( [related-headline] => Street Outlaws Turbo Rotary Mazda RX-7 – OKC NoPrep [related-url] => //localhost:3000/street-outlaws-turbo-rotary-mazda-rx-7-okc-noprep/ [related-image_id] => 78055 [related-image] => //localhost:3000/wp-content/uploads/2015/12/lucky-to-be-alive-distracted-dri.jpg ) [1] => Array ( [related-headline] => In the Driver’s Seat: Shane vs. The Reaper | Street Outlaws [related-url] => //localhost:3000/in-the-drivers-seat-shane-vs-the-reaper-street-outlaws/ [related-image_id] => 78048 [related-image] => //localhost:3000/wp-content/uploads/2015/12/ford-f350-vs-dodge-ram-vs-chevy.jpg ) ) ) 

这是我的代码:

$entries = get_post_meta( get_the_ID(), 'ss-related-posts' );
// print_r($entries);

foreach ( (array) $entries as $key => $entry ) {
    $title = '';
    $title = $entry['related-headline'];
    echo $title;
}

我知道我在这里缺少一些简单的东西,所以任何帮助将不胜感激。

php 数组 wordpress foreach undefined-index

评论

0赞 Rizier123 12/31/2015
看看你的数组是如何嵌套的:Array ( [0] => Array ( [0] => Array ( ; (array) $entries -> (array) $entries[0]
0赞 Joe Conlin 12/31/2015
我意识到这一点,但这就是它从 WP 回来的方式,所以我需要以某种方式使用它。
0赞 Rizier123 12/31/2015
有关修复;),请参阅分号后面的部分
1赞 Rizier123 12/31/2015
啊,只需删除数组转换,只是:(忘记在我之前的评论中删除它)foreach ( $entries[0] as $key => $entry ) {
2赞 random_user_name 12/31/2015
将此行:更改为: - “TRUE”表示它是单个值,并将减少数组的一个级别。$entries = get_post_meta( get_the_ID(), 'ss-related-posts' );$entries = get_post_meta( get_the_ID(), 'ss-related-posts' , TRUE);

答:

0赞 Joe Conlin 12/31/2015 #1

我通过简单地按照cale_b的评论中的建议添加到函数调用来让它工作:TRUE

$entries = get_post_meta( get_the_ID(), 'ss-related-posts', TRUE );

foreach ( (array) $entries as $key => $entry ) {
    $title = $url = $img = "";
    $title = $entry['related-headline'];
    $url = $entry['related-url'];
    $img = $entry['related-image'];

    echo $title . "<br>" . $url . "<br>" . $img . "<br>";
}