Jump to content

foreach varaiable as array


troshan
Go to solution Solved by requinix,

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
Share on other sites

  • Solution

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().
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.