dongxian8858 2016-11-15 08:35
浏览 203
已采纳

Wordpress在自定义字段的查询中输出到数组

I have created a custom field named "sec1array" in my categories so that i can add an array, for example 1,2,3,4

I want to retrieve that array and output it in the loop, so I created this code.

$seconearray = array($cat_data['sec1array']);

$args = array( 
'post__in' => $seconearray
);

However, it only seems to be outputting the first post in the array. Is it something to do with the way the comma is outputting?

If I print $seconearray it outputs correctly, example 1,2,3,4

  • 写回答

1条回答 默认 最新

  • douyi6755 2016-11-15 08:47
    关注

    What you are doing is storing a string value of "1,2,3,4" in your database which when you are trying to construct an array from it like array("1,2,3,4") you end up just assigning a single value to that new array. This is why it only contains a single value.

    You need to store your value in a serializable format so it can be converted back to an array after you save it to the database. There are many ways to do this, I'm sure others will give more examples:

    JSON encode it

    json_encode(array(1,2,3,4)); // store this in your db
    json_decode($cat_data['sec1array']); // outputs an array
    

    Or, you can use PHP serialize

    serialize(array(1,2,3,4)); // store this in your db
    unserialize($cat_data['sec1array']); // outputs an array
    

    If you want to keep your string, you can explode it:

    explode(',', $cat_data['sec1array']); // outputs your array of 1,2,3,4.
    

    Using any of these methods will work. Finally you'll end up with an example like:

    $seconearray = explode(',', $cat_data['sec1array']);
    $args = array( 
        'post__in' => $seconearray
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 TMUXHS4412如何防止静电,
  • ¥30 Metashape软件中如何将建模后的图像中的植被与庄稼点云删除
  • ¥20 机械振动学课后习题求解答
  • ¥15 IEC61850 客户端和服务端的通讯机制
  • ¥15 MAX98357a(关键词-播放音频)
  • ¥15 Linux误删文件,请求帮助
  • ¥15 IBMP550小型机使用串口登录操作系统
  • ¥15 关于#python#的问题:现已知七自由度机器人的DH参数,利用DH参数求解机器人的逆运动学解目前使用的PSO算法
  • ¥15 发那科机器人与设备通讯配置
  • ¥15 Linux环境下openssl报错
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部