0

我正在使用ACF 的 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++;

}

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

在此处输入图像描述

4

1 回答 1

0

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

我停止了它附加到$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++;

}
于 2018-06-28T12:21:09.767 回答