【问题标题】:Iteration copying over itself on loop循环复制自身的迭代
【发布时间】:2018-06-28 08:57:39
【问题描述】:

我正在使用ACF's update_sub_field 函数将循环中的内容添加到子转发器字段。

我已经达到了将数据添加到子中继器但它会覆盖自身的地步。它只会更新子中继器中的第一行,所以我只会看到最后一个循环。

我正在使用$counter 迭代父转发器,但是当我尝试向子转发器添加迭代时,它会破坏函数。像这样:

update_sub_field( array($field_key, $counter, $sub_field_key, $rowcount), $value, $post_id );

我已经尝试了另一个函数add_sub_row...这会将正确的行数添加到子转发器的行中,但不会添加数据。

这是我的完整代码:

// Product Code Titles
$rows = $html->find('div[class=product-table]', 0)->find('tr');
$field_key = "field_5ae0882f9d6f9";
$sub_field_key = "field_5ae088999d6fb";

if(empty($rows)){
    die("Empty array");
}

$titles = array(); // aka your $data

// here we fetch the first row and iterate to get titles
$row = current($rows);
foreach ($row->find('td') as $cell) {
    $titles[] = array("column_title" => strip_tags($cell->innertext));
}
update_field( $field_key, $titles, $post_id );

// here we continue iteration starting from second row
$value = array();
$rowcount = 1;
while($row = next($rows)){

    $cells = $row->find('td');
    $columnsCount = count($cells);
    $counter = 1;
    foreach ($cells as $cell) {
      $value[] = array("text" => strip_tags($cell->innertext));
      update_sub_field( array($field_key, $counter, $sub_field_key), $value, $post_id );
      echo '<pre>'; print_r($value); echo '</pre>';
      $value = array();
      $counter++;
    }

  $rowcount++;

}

只是为了提供一些上下文,我正在重新创建此表,并将单元格数据放入子转发器字段中。

【问题讨论】:

    标签: php advanced-custom-fields


    【解决方案1】:

    关于这个主题的内容不多,所以希望这对其他人有所帮助。

    我停止将它附加到 $value 数组,将函数更改为 update_sub_row 并添加了一个计数器来迭代子转发器行。

    这是完整的代码:

    // Product Code Titles
    $rows = $html->find('div[class=product-table]', 0)->find('tr');
    $field_key = "field_5ae0882f9d6f9";
    $sub_field_key = "field_5ae088999d6fb";
    
    if(empty($rows)){
        die("Empty array");
    }
    
    $titles = array(); // aka your $data
    
    // here we fetch the first row and iterate to get titles
    $row = current($rows);
    foreach ($row->find('td') as $cell) {
        $titles[] = array("column_title" => strip_tags($cell->innertext));
    }
    update_field( $field_key, $titles, $post_id );
    
    // here we continue iteration starting from second row
    $value = array();
    $rowcount = 1;
    while($row = next($rows)){
    
        $cells = $row->find('td');
        $columnsCount = count($cells);
        $counter = 1;
        foreach ($cells as $cell) {
          $value = array("field_5ae088b79d6fc" => strip_tags($cell->innertext));
          update_sub_row( array($field_key, $counter, $sub_field_key), $rowcount, $value, $post_id );
          echo '<pre>'; print_r($value); echo '</pre>';
          $value = array();
          $counter++;
        }
    
      $rowcount++;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多