phparrayswordpresswoocommercecustom-data-attribute

Change format of array generated through WooCommerce


I am generating an array of woocommerce attributes with the following code:

$customAttributes = array();
    $attributes = $product->get_attributes();
    foreach($attributes as $attr=>$attr_deets){
        $attribute_label = wc_attribute_label($attr);
        if ( isset( $attributes[ $attr ] ) || isset( $attributes[ 'pa_' . $attr ] ) ) {
            $attribute = isset( $attributes[ $attr ] ) ? $attributes[ $attr ] : $attributes[ 'pa_' . $attr ];
            if ( $attribute['is_taxonomy'] ) {
                array_push($customAttributes,  array(
                    $attribute_label => implode( ', ', wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ) )
                ));
            } else {
                array_push($customAttributes,  array(
                    $attribute_label => $attribute['value']
                ));
            }
        }
    }

The above code works fine and outputs the following code array:

{
    "att-1": "value 1 | value 2"
  },
  {
    "att-2": "value 1 | value 2"
  }

I want to change its format to:

{
      "type": "att-1",
      "value": "value 1",
      "value": "value 2"
    },
    {
      "type": "att-2",
      "value": "value 1",
    "value": "value 2",
    },

type and value are static

I have tried changing it but, can't figure out how to make it worked as required.

Thanks for the help and looking forward to a solution from pros.

Ahmad


Solution

  • Nevermind, I found out that is not possible and is also not a proper syntax for array and I managed to get the following code working:

        {
        "att-1": "value 1 | value 2"
      },
      {
        "att-2": "value 1 | value 2"
      }