For some reason I can’t use a variable as my index to an associative array? $myarray[“myindex”];.
Overview: I’m building a calendar schedule plugin that use WP Options API for use on a site.
The options set upon plugin initialization:
The jsn_event_list is all that matters and I’ve stripped the other elements of the array out for easy reading. jsn_event_list is just an array of json objects related to 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 the function that receives a AJAX request to update the options 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 that using myarray[$myvar] works and I proved this by doing a quick two liner test but it doesn’t work here… I tried casting (string) $post_option_name but nope. Any ideas?