高级自定义字段(ACF) - 循环通过中继器结帐字段,并输出每个值的单个实例



我有一个WordPress页面,该页面可以循环通过产品列表。这些产品是使用ACF中继器场创建的。每种产品都有一个或多个使用复选框字段应用的一个或多个属性(例如,光,深色,金属色彩,丰富多彩)。

目的是查询页面上所有产品的复选框中继器字段,请查看单独分配给每个产品的属性,并输出所有产品的单个列表(删除重复项)。

例如,如果有十种产品,并且它们在它们之间被标记为四个唯一属性,则只能输出四个唯一属性。

我已经尝试创建一个空数组,然后循环循环。当前循环输出重复值(例如light dark light dark light dark而不是light dark

<?php if (have_rows('product')): while (have_rows('product')) : the_row(); 
    $attributes = get_sub_field_object('product_attributes'); 
    $values = $attributes['value'];  
    if($values) {
        $filter_attributes = array();
        foreach ($values as $value) {
            if (in_array($attributes, $filter_attributes)) {
                continue;
            }
        $filter_attributes[] = $attributes;
        echo $value . " ";
    } 
} endwhile; endif; ?>

您的代码有很多问题,因此我们确实需要重新开始。根据您提供的内容,并且不知道如何设置ACF中继器,我认为以下内容应该适合您。

您想做的是:

  1. 循环浏览您的中继器中的所有产品
  2. 从您的product_attributes获取所有值
  3. 上获取唯一 products
  4. 在同一条线上显示唯一值,被空间隔开

您遇到的主要问题是获得唯一的数组。有多种方法可以做到这一点,您选择了最复杂的:)

1。使用in_array检查以前的值

这是您目前尝试这样做的方式,但是您对逻辑有问题。因此,我会建议选项2,但是对于完整性,这是您应该做的:

$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row(); 
    $attributes = get_sub_field_object('product_attributes'); 
    $values = $attributes['value'];  
    if($values) {
        foreach ($values as $value) 
            if (!in_array($value, $filter_attributes)) {
                $filter_attributes[] = $value;
            }
    } 
} endwhile; endif;
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );

2。使用array_nique

代码比上一个选项要简单得多。您可以将所有所有值保存到一个数组中,然后在最后使用array_unique(php.net array_unique)。这消除了每次检查现有值的需求。例如

$all_attributes = array();
$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row(); 
    $attributes = get_sub_field_object('product_attributes'); 
    $values = $attributes['value'];  
    if($values) {
        foreach ($values as $value) 
            $all_attributes[] = $value; /* Save ALL values */
    } 
} endwhile; endif;
/* use array_unique to remove duplicates from the array */
$filter_attributes = array_unique ($all_attributes);
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );

3。使用数组键

如果您使用数组键的值,则将确保每个值在数组中不允许重复键。这是有点骇客的方式,但是它很快&amp;简单:)

$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row(); 
    $attributes = get_sub_field_object('product_attributes'); 
    $values = $attributes['value'];  
    if($values) {
        foreach ($values as $value) 
            /* if  $all_attributes[$value] already exists, this will overwrite it 
               ensuring the array only has unique values */
            $all_attributes[$value] = $value;
    } 
} endwhile; endif;
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );

最新更新