Skip to content
Advertisement

How to filter an object array in php by value of a parameter?

I’m new to php and I’m trying to filter an array of fields so that it only contains fields that have required property.

In javascript I would do it simply by:

fields.filter(field => field.required)

but I have no idea how to do it in php.

I’m quite new to php syntax, and have been unsuccessful with implementing array_filter. I’m trying to edit woocommerce template to only show required fields. This is what each field has:

$fields['billing']['billing_email'] = array(
        'label'     => __('Email', 'woocommerce'),
        'placeholder'   => _x('EMAIL', 'placeholder', 'woocommerce'),
        'required'  => true,
        'clear'     => true
    );

My $fields array should be only objects that have required = true

foreach ( $fields as $key => $field ) {

            //billing style argument fields. start
            $key_gap_list = array('billing_last_name', 'billing_company', 'billing_country', 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_phone');

            if (!isset($field['placeholder']) && isset($field['label'])) {
                $field['placeholder'] = $field['label'];
            }
            if (isset($field['required']) && $field['required']) {
                $field['placeholder'] .= ' *';
            }
            if (isset($field['class'])) {
                $findClass = array_search('form-control', $field['class']);
                if ($findClass) {
                    unset($field['class'][$findClass]);
                }
            }
            $field['input_class'] = array('form-control');
            unset($field['label']);

            //billing style argument fields. end
            if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) {
                $field['country'] = $checkout->get_value( $field['country_field'] );
            }

            woocommerce_form_field( $key, $field, $checkout->get_value( $key ) );

            if ($key == 'billing_last_name') {
                echo '<div class="clear"></div>';
            }
        }

Advertisement

Answer

I managed to solve the issue by overriding the woocommerce checkout template and added custom fields and removed the ones I didn’t need. The project is closed so I cannot share any code of how I did it, but I’m closing this issue.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement