PHP associative array can't use variable as index?

For some reason, I cannot use a variable as my index for an associative array? $ MyArray ["myindex"] ;.

Overview. I am creating a calendar schedule plugin that uses the WP Options API to be used on a site.

Parameters set during plugin initialization:

Whatever matters to jsn_event_list, I've removed the other elements of the array for readability. jsn_event_list is just an array of json objects associated with specific events.

        $arr = array( "jsn_event_list" => '[{"date": "May 12, 2012", "type":"Breakfast","location":"Victoria"},{"date": "May 10, 2012", "type":"Breakfast","location":"Victoria"}, {"date": "May 7, 2012", "type":"Breakfast","location":"Victoria"}, {"date": "May 30, 2012", "type":"Breakfast","location":"Victoria"}, {"date": "May 29, 2012", "type":"Breakfast","location":"Victoria"}, {"date": "May 31, 2012", "type":"Breakfast","location":"Victoria"}]'
    );

    update_option('cal_sched_options', $arr);

      

Here's a function that receives an AJAX request to update parameters from the plugins page:

function ajax_calendar_schedule_options() 
{
    // Get WP options
    $wp_plugin_option_name = 'cse_calendar_schedule_options';
    $wp_options = get_option($wp_plugin_option_name); // array of options listed above

    // Get post information
    $post = $_POST['data'];
    // EDITED LINE FROM:
    //$post_option_name = $post['option_name']; // HELP: option_name = string (13) "jsn_event_list" when var_dump($post['option_name']); BUT DOES NOT WORK WHEN $post_option_name IS USED TO INDEX BELOW ARRAYS
    // EDITED LINE TO:
    $post_option_name = "jsn_event_list"; // WORKS WHEN HARDCODED TO SAME VALUE AND USED IN BELOW ARRAYS TO INDEX 
    $post_option_value = $post['option_value']; // associative array = Array([date] => Mar 14, 2012, [type] => Dinner, [location] => Vancouver)

    // Get WP option using post option name
    $wp_option = $wp_options[$post_option_name];
    $wp_option = json_decode( $wp_option ); // array = Array([0] => stdClass Object( [date] => May 12, 2012, [type] => Breakfast, [location] => Victoria) ... etc )

    // Update by appending post as new array element
    $wp_option[] = $post_option_value;

    // Overwrite the changes with json string
    $wp_options[$post_option_name] = json_encode( $wp_option );

    // Save and sanitize (using cse_calendar_schedule_validate_options) changes
    update_option( $wp_plugin_option_name, $wp_options ); 

    // Return updated event list
    echo $wp_options[$post_option_name];

    die(); // Required to return a proper result
}

      

I know using myarray [$ myvar] works and I proved it by doing a quick test with two liners, but it doesn't work here ... I tried casting (string) $ post_option_name but nope. Any ideas?

+3


source to share





All Articles