Jump to content

foreach varaiable as array


troshan

Recommended Posts

Following code generate a select dropdown field
 

$fields['shipping']['shipping_city'] = array(
    'label'       => __('City', 'woocommerce'),
    'placeholder' => _x('', 'placeholder', 'woocommerce'),
    'required'    => true,
    'clear'       => true,
    'type'        => 'select',
    'class'       => array('own-css-name'),
    'options'     => array(
        'New_York_City' => __('New York City', 'woocommerce' ),
        'Chicago' => __('Chicago', 'woocommerce' ),
        'Dallas' => __('Dallas', 'woocommerce' )
        )
    );



I want to get the "option =>" values from category array. I tried the following

$categories = get_categories( $args );
    foreach ($categories as $category) {
    $cityArray[] = "'".$category->slug."' => __('".$category->name."', 'woocommerce' )";
    }
    $fields['shipping']['shipping_city2'] = array(
        'label'       => __('City', 'woocommerce'),
        'placeholder' => _x('', 'placeholder', 'woocommerce'),
        'required'    => true,
        'clear'       => true,
        'type'        => 'select',
        'class'       => array('own-css-name'),
        'options'     => array(implode( ', ', $cityArray ) )
 );


but It return the attached result
 

post-179153-0-72209400-1435207987_thumb.jpg

Link to comment
https://forums.phpfreaks.com/topic/297015-foreach-varaiable-as-array/
Share on other sites

Unfortunately that's quite wrong. The "options" needs to be an array where the keys are what you want the value of each to be, and the value is what shows up as the label for it. What you're doing is

1. Taking the array of categories

2. Making another array where each value is a string of PHP code

3. implode()ing the array so that it's only one string with comma separators

4. Sticking that into an array

 

The $cityArray needs to be formed correctly. $category->slug should be the key and the translated $category->name should be the array value.

$cityArray[$category->slug] = __($category->name, 'woocommerce');
Then don't do anything else to it. Just use it as the "options". No array(), no implode().

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.