1

在 Wordpress 中,我试图从头开始创建一个元框脚本,以更好地理解 Wordpress 和 PHP。

不过,我在多维数组上的 for each 循环中遇到了一些问题。我正在使用 PHP5。

这是数组:

$meta_box = array();    
$meta_box[] = array(
            'id' => 'monitor-specs',
            'title' => 'Monitor Specifications',
            'context' => 'normal',
            'priority' => 'default',
            'pages' => array('monitors', 'products'),
            'fields' => array(
                array(
                    'name' => 'Brand',
                    'desc' => 'Enter the brand of the monitor.',
                    'id' => $prefix . 'monitor_brand',
                    'type' => 'text',
                    'std' => ''
                )
            )
        );

这是每个循环:

foreach ($meta_box['pages'] as $post_type => $value) {
            add_meta_box($value['id'], $value['title'], 'je_format_metabox', $post_type, $value['context'], $value['priority']);
        }

我要做的是循环遍历“pages”数组中的键,该数组是“meta_box”数组中的一个数组,同时能够使用“meta_box”数组的键值。

我需要为每个循环嵌套一些吗?

将不胜感激一些正确方向的指示,以便我可以解决这个问题。

4

5 回答 5

1

您的foreach开头是$meta_box['pages'],但没有$meta_box['pages']

你确实有一个$meta_box[0]['pages'],所以你需要两个循环:

foreach($meta_box as $i => $box)
    foreach($box['pages'] as $page)
        add_meta_box(.., ..); // do whatever

您期望$value变量中包含什么?

于 2011-12-07T12:16:20.507 回答
1
foreach ($meta_box[0]['pages'] as $post_type => $value) {

或者

$meta_box = array(...
于 2011-12-07T12:16:26.983 回答
1

这里:

$meta_box = array();    
$meta_box[] = array(......

表明没有 $meta_box['pages']。meta_box 是一个带有数字索引的数组(检查 [] 运算符),它的每个元素都是一个具有键“pages”的数组。

因此您需要在 $meta_box 上使用 foreach,并且在每个元素上您需要使用 pages 键。如您所见,id、title、context 是与 pages 处于同一级别的元素

于 2011-12-07T12:17:21.107 回答
1

您引用了错误的数组键

$meta_box[] <-- $meta_box[0]

但是,您指的是使用:-

foreach ($meta_box['pages'] as $post_type => $value) {

添加数组键将解决问题:-

foreach ($meta_box[0]['pages'] as $post_type => $value) {
于 2011-12-07T12:17:50.383 回答
1

也许创建一些类来保存这些信息可能会很好。

class Metabox
{
  public $id, $title, $context, $priority, $pages, $fields;

  public function __construct($id, $title, $pages, $fiels, $context='normal', $priority='default')
  {
    $this->id = $id;
    $this->title = $title;
    $this->pages = $pages;
    $this->fields = $fields;
    $this->context = $context;
    $this->priority = $priority;
  }

}

$meta_box = array();

$meta_box[] = new Metabox(
  'monitor-specs', 
  'Monitor Specifications', 
  array('monitors', 'products'),
  array(
    'name' => 'Brand',
    'desc' => 'Enter the brand of the monitor.',
    'id' => $prefix . 'monitor_brand',
    'type' => 'text',
    'std' => ''
  )
);

现在您可以循环遍历 meta_box 数组,例如:

foreach ($meta_box as $box)
{
  add_meta_box($box->id, $box->title, .. and more)
  // This function could be placed in the metabox object

  /* Say you want to access the pages array : */
  $pages = $box->pages;

  foreach ($pages as $page)
  {
    ..
  }
}

现在你仍然有一个循环,但可能有助于更清楚地看到你的问题。

于 2011-12-07T12:29:22.563 回答