【问题标题】:WordPress: get data from array in databaseWordPress:从数据库中的数组中获取数据
【发布时间】:2014-09-24 13:51:56
【问题描述】:

我有动态创建的自定义字段。我从这些字段中获取数据并将其作为带有update_post_meta 的数组存储到数据库中。它以序列化数组的形式存储在数据库中:

a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}

现在我需要得到这个数组并在网站上回显它,所以它看起来像:4 个孩子 (1993,1994,1995,1996)。

这是我现在使用的代码,但它不起作用。

<?php
$children = get_post_custom_values('rbchildyear');

foreach ($children as $key => $value){
  echo "$key => $value('rbchildyear')<br>";
}
?>

这就是我在前台得到的:

0 => a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}('rbchildyear')

那我该怎么做呢?

谢谢!

【问题讨论】:

  • 你在 $children 中得到了什么?
  • 它是一个带有name="rbchildyear[]"的输入文本字段。

标签: php arrays wordpress loops serialization


【解决方案1】:

使用反序列化()。

$children = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');

print_r($children);

这将返回数组

【讨论】:

  • 在 WordPress 中有 get_post_meta() 反序列化数据和 get_post_custom_values() 返回包含所有值的数组,我需要以某种方式使用它们,只是无法弄清楚我到底做错了什么。
【解决方案2】:

如果您使用 get_post_meta,它将返回一个值数组(数字索引)。然后你可以用 foreach 循环遍历数组。

$childYears = get_post_meta($post_id, "rbchildyear", true);

foreach($childYears AS $theYear)
{
     $printThis .= $theYear.",";
}

print count($childYears)." children ( ".$printThis." )";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    相关资源
    最近更新 更多