簡體   English   中英

PHP-對於每個循環問題

[英]PHP - For each loop problems

在Wordpress中,我試圖從頭開始創建一個metabox腳本,以更好地理解Wordpress和PHP。

我在多維數組上的for每個循環都有一些問題。 我正在使用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'數組中的鍵,而'pages'數組是'meta_box'數組內的一個數組,同時能夠使用'meta_box'數組的鍵值。

我需要為每個循環嵌套一些嗎?

對於某些正確方向的指針,我們將不勝感激。

您的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變量中包含什么?

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

要么

$meta_box = array(...

這里:

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

建議沒有$ meta_box ['pages']。 meta_box是具有數字索引的數組(請檢查[]運算符),其每個元素都是具有鍵“ pages”的數組。

因此,您需要在$ meta_box上使用foreach,並且在每個元素上都需要使用pages鍵。.id,title,context是與頁面處於同一級別的元素,如您所見

您引用了錯誤的數組鍵

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

但是,您使用:-

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

添加數組鍵將解決問題:-

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

創建某個類來保存此信息可能會很好。

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)
  {
    ..
  }
}

現在您仍然有一個循環,但是也許可以幫助您更清楚地看到問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM