I try to generate Donut chart code using Json array. I have stuck with in one place
This is my code
<?php
$canvas_data = array(
'type' => 'doughnut',
'data' => array(
'labels' => array(), // this array will be populated from the repeater
'datasets' => array(
'label' => '',
'backgroundColor' => array('#4e73df', '#1cc88a','#36b9cc','#df4e75'),
'borderColor'=> array('#ffffff','#ffffff','#ffffff','#ffffff'),
'data' => array() // this array will be populated from the repeater
)
),
'options' => array(
'maintainAspectRatio' => false,
'legend' => array(
'display' => false,
),
'title' => array()
),
);
// loop over repeater and populate object
if (have_rows('donut_graph_details')) {
while (have_rows('donut_graph_details')) {
the_row();
$canvas_data['data']['labels'][] = get_sub_field('title');
$canvas_data['data']['datasets']['data'][] = get_sub_field('percentage');
}
}
// use json encode to output attribute
?>
<canvas data-bs-chart='<?php echo json_encode($canvas_data); ?>'></canvas>
Out put using this code
<canvas data-bs-chart='{"type":"doughnut","data":{"labels":["IMPLEMENTED","PARTIALLY IMPLEMENTED","NOT IMPLEMENTED","UNDISCLOSED"],"datasets":{"label":"","backgroundColor":["#4e73df","#1cc88a","#36b9cc","#df4e75"],"borderColor":["#ffffff","#ffffff","#ffffff","#ffffff"],"data":["40","30","10","20"]}},"options":{"maintainAspectRatio":false,"legend":{"display":false},"title":[]}}'></canvas>
But I want to do small modification to the Out put. I want to add "[" before starting "datasets" and wants to close it . I have add the modification code below.
<canvas data-bs-chart='{"type":"doughnut","data":{"labels":["IMPLEMENTED","PARTIALLY IMPLEMENTED","NOT IMPLEMENTED","UNDISCLOSED"],"datasets":[{"label":"","backgroundColor":["#4e73df","#1cc88a","#36b9cc","#df4e75"],"borderColor":["#ffffff","#ffffff","#ffffff","#ffffff"],"data":["40","30","10","20"]}]},"options":{"maintainAspectRatio":false,"legend":{"display":false},"title":[]}}'></canvas>
Related
Inside a foreach loop I am assigning an array to a variable.
Because this array is within a loop it will output more than once.
Because it will output more than once I need the end of the array to have a comma so it doesn't break the array for each time it returns and instance of the array.
Is there a way to do this?
- I found ways online but they only showed how to do this with strings in foreach loops, to either add or remove the comma at the end of the last foreach loop.
My code is below to explain.
// ----------------------------------------------------------------------------------------------------
// Start our framework config arrays
// ----------------------------------------------------------------------------------------------------
$options = array();
// ----------------------------------------------------------------------
// MENU - Layout Settings
// ----------------------------------------------------------------------
$options[] =
array(
'title' => 'Layout Settings',
'name' => 'layout-settings',
'icon' => 'fa fa-cog',
'fields' =>
array(
// ----------------------------------------------------------------------
// TAB - Layout Settings
// ----------------------------------------------------------------------
array('type' => 'tabbed', 'id' => 'layout_settings', 'tabs' => array(
return_post_type_layout_settings()
))
),
);
// Our return array function
function return_post_type_layout_settings() {
$public_post_type = get_post_types(
array(
'_builtin' => TRUE,
'public' => TRUE
)
);
sort($public_post_type, SORT_NATURAL);
foreach($public_post_type as $post_type) {
$layout_options =
array('title' => ucwords($post_type) . ' Layout', 'fields' => array(
array('id' => $post_type, 'type' => 'grid', 'span' => '6-12', 'fields' => array(
// ----------------------------------------------------------------------
// FIELD - Header Settings Panel
// ----------------------------------------------------------------------
array('message' => 'Enable ' . ucwords($post_type). ' Header Settings?', 'video' => 'QAEjuDpIaE4', 'type' => 'title_with_help'),
array('id' => $post_type . '_enable_header', 'type' => 'switcher'),
))
)) // << I need to comma to post at the end of this array
// because in my array above this will output more than once
;
return $layout_options;
}
}
Multiple issues with the code. And there is nothing to do with actual commas. But rather the data structure of function output.
Code Receiving the Function output
In this piece of code:
<?php
$options[] =
array(
'title' => 'Layout Settings',
'name' => 'layout-settings',
'icon' => 'fa fa-cog',
'fields' =>
array(
// ----------------------------------------------------------------------
// TAB - Layout Settings
// ----------------------------------------------------------------------
array('type' => 'tabbed', 'id' => 'layout_settings', 'tabs' => array(
return_post_type_layout_settings()
))
),
);
The tabs is declared only as an array with 1 value. There is no way you can put multiple value into tabs like this. It should be modified like this:
<?php
$options[] =
array(
'title' => 'Layout Settings',
'name' => 'layout-settings',
'icon' => 'fa fa-cog',
'fields' =>
array(
// ----------------------------------------------------------------------
// TAB - Layout Settings
// ----------------------------------------------------------------------
array('type' => 'tabbed', 'id' => 'layout_settings', 'tabs' => return_post_type_layout_settings())
),
);
The Function
Then you need to modify your function to return the correct array format:
function return_post_type_layout_settings() {
$public_post_type = get_post_types(
array(
'_builtin' => TRUE,
'public' => TRUE
)
);
sort($public_post_type, SORT_NATURAL);
$layout_options = array(); // initialize $layout_options as array
foreach($public_post_type as $post_type) {
// append each options into $layout_options
$layout_options[] =
array('title' => ucwords($post_type) . ' Layout', 'fields' => array(
array('id' => $post_type, 'type' => 'grid', 'span' => '6-12', 'fields' => array(
// ----------------------------------------------------------------------
// FIELD - Header Settings Panel
// ----------------------------------------------------------------------
array('message' => 'Enable ' . ucwords($post_type). ' Header Settings?', 'video' => 'QAEjuDpIaE4', 'type' => 'title_with_help'),
array('id' => $post_type . '_enable_header', 'type' => 'switcher'),
))
));
}
// return after $layout_options is finished
return $layout_options;
}
Is the goal to have $layout_options be an array of multiple ["title"=>"My Layout", "fields"=>[..]] objects? If so, I'd do something like this:
function return_post_type_layout_settings() {
$public_post_type = get_post_types(
array(
'_builtin' => TRUE,
'public' => TRUE
)
);
sort($public_post_type, SORT_NATURAL);
$layout_options = array();
foreach($public_post_type as $post_type) {
$layout_options[] =
array('title' => ucwords($post_type) . ' Layout', 'fields' => array(
array('id' => $post_type, 'type' => 'grid', 'span' => '6-12', 'fields' => array(
// ----------------------------------------------------------------------
// FIELD - Header Settings Panel
// ----------------------------------------------------------------------
array('message' => 'Enable ' . ucwords($post_type). ' Header Settings?', 'video' => 'QAEjuDpIaE4', 'type' => 'title_with_help'),
array('id' => $post_type . '_enable_header', 'type' => 'switcher'),
))
))
;
}
return $layout_options;
}
What I am trying to achieve is create a jQuery Tabs markup from PHP Array. Basic intention is to add tabs and content dynamically. Both existing StackExchange answers and Google Search left me empty handed here. Finding it pretty dificult with my level of PHP knowledge.
Here are one of the many code that I have tried:
My Array:
$args = array();
$args[] = array(
'name' => 'Shortcode Name',
'tabname' => 'Shortcode Tab Name', //Same As Tab 4
'action' => 'shortcodeaction',
'icon' => 'codeicon',
'image' => 'codeimage',
);
$args[] = array(
'name' => 'Shortcode2 Name',
'tabname' => 'Shortcode2 Tab Name',
'action' => 'shortcodeaction2',
'icon' => 'codeicon2',
'image' => 'codeimage2',
);
$args[] = array(
'name' => 'Shortcode3 Name',
'tabname' => 'Shortcode3 Tab Name',
'action' => 'shortcodeaction3',
'icon' => 'codeicon3',
'image' => 'codeimage3',
);
$args[] = array(
'name' => 'Shortcode4 Name',
'tabname' => 'Shortcode Tab Name', //Same As Tab 1
'action' => 'shortcodeaction4',
'icon' => 'codeicon4',
'image' => 'codeimage4',
);
$args[] = array(
'name' => 'Shortcode5 Name',
'tabname' => 'Shortcode5 Tab Name',
'action' => 'shortcodeaction5',
'icon' => 'codeicon5',
'image' => 'codeimage5',
);
The PHP Code:
echo '<ul>';
foreach ( $args as $arg ) {
echo '<li>'.$arg['tabname'].'</li>';
}
echo </ul>
foreach ( $args as $arg ) {
echo '<div id="' . preg_replace("/[^a-z0-9]+/", "", $arg['tabname'] ) . '"></div>';
}
The tabname key value for Tab 1 and Tab 4 are same, so they should go under same tab name and tab content. This is exactly where I am getting lost. I know I can do a foreach loop to create tabs, but those two are not going under same tab instead they are creating new tab with same name.
Used this to get the count for array with unique value for tabname:
$lists = wp_list_pluck( $args, 'tabname' );
$counts = count( array_unique( $lists ));
// 4
Now a foreach loop will create 3 tabs, but not sure how to pass the $args inside the loops.
I am not asking you to do this for me, but a little head start would be great.
Thanks
here I am seeing a small problem, I have two tables template and template_text, in template table I store the template type and visibility data and in the template_text table I store the template text in many languages, atm. I have two langs. such as EN and DE. So, when I am editing the template I preload the current template values into the form, but there is a problem with the values like autoemailer_title and autoemailer_body, when the from helper generates the form field it is generating this fields this way autoemailer_title_1, autoemailer_title_2 according the language ID, so, the question would be how to preload all this values the right way? I could use javascript and ajax get request to get the values and then set them by using the input ID, but I think there is a better way using the form helper.
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l($params['title']),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'select', // This is a <select> tag.
'label' => $this->l('Template type'), // The <label> for this <select> tag.
'desc' => $this->l('Choose a template type'), // A help text, displayed right next to the <select> tag.
'name' => 'autoemailer_type', // The content of the 'id' attribute of the <select> tag.
'required' => true, // If set to true, this option must be set.
'options' => array(
'query' => array(
array(
'id_option' => 'static', // The value of the 'value' attribute of the <option> tag.
'name' => 'Static' // The value of the text content of the <option> tag.
),
array(
'id_option' => 'dynamic',
'name' => 'Dynamic'
),
), // $options contains the data itself.
'id' => 'id_option', // The value of the 'id' key must be the same as the key for 'value' attribute of the <option> tag in each $options sub-array.
'name' => 'name' // The value of the 'name' key must be the same as the key for the text content of the <option> tag in each $options sub-array.
)
),
array(
'type' => 'text',
'label' => $this->l('News letter title'),
'name' => 'autoemailer_title',
'desc' => $this->l('Title'),
'lang' => true,
// 'style' => 'width:300px',
'class' => 'fixed-width-lg',
),
array(
'type' => 'textarea',
'label' => $this->l('Text'),
'name' => 'autoemailer_body',
'desc' => $this->l('Email body'),
'lang' => true,
'cols' => 60,
'rows' => 10,
'class' => 'rte', // we need this for setuping the tiny mce editor
'autoload_rte' => true, // we need this for setuping the tiny mce editor
),
),
'submit' => array(
'title' => $this->l('Save')
)
)
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'newTemplate';
$helper->currentIndex = $this->getThisUrl() . '&emailer_action=main';
$helper->token = Tools::getAdminTokenLite('AdminModules');
return $helper->generateForm(array($fields_form));
Solved this one. So, when we have more than one lang then the attribute for which we apply the multilangiage option becomes an array, so to set the value according the language we can just do this way :
$lang_id = 1; // setting the language ID, usually it's done by foreaching the records from ps_lang table
$helper->fields_value['description'][$lang_id] = 'my default value'; // setting the default value
return $helper->generateForm(array($fields_form)); // returning the output of generated form
I have the following two things:
$_POST array with posted data
$params array with a path for each param in the desired data array.
$_POST = array(
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
I would like to generate the $data array like the example below.
How can I do that?
Notice how the "paths" from the $params array are used to build the keys for the data array, filling it with the data from the $_POST array.
$data = array(
'User' => array(
'name' => 'Marcus',
),
'Page' => array(
'published' => 'Today',
'Data' => array(
'url' => 'http:://example.com',
'layout' => 'Some info...',
),
),
);
I would use referenced variables:
$post = array( // I renamed it
'name' => 'Marcus',
'published' => 'Today',
'url' => 'http:://example.com',
'layout' => 'Some info...',
);
$params = array(
'name' => 'Invoice.name',
'published' => 'Page.published',
'url' => 'Page.Data.url',
'layout' => 'Page.Data.layout',
);
echo '<pre>'; // just for var_dump()
foreach($post as $key=>$var){ // take each $_POST variable
$param=$params[$key]; // take the scheme fields
$path=explode('.',$param); // take scheme fields as an array
$temp=array(); // temporary array to manipulate
$temp_original=&$temp; // we need this the same as we're going to "forget" temp
foreach($path as $pathvar){ // take each scheme fields
$temp=&$temp[$pathvar]; // go deeper
}
$temp=$var; // that was the last one, insert it
var_dump($temp_original); // analize carefully the output
}
All you have to do now is to combine them all, they are not exactly what you want, but this will be easy.
And please note, that each $temp_original fields are pointing at $post variable data! (&string instead of string). You may want to clone it somehow.
I'm querying the instagram api to return json with this code:
$instagramClientID = '9110e8c268384cb79901a96e3a16f588';
$api = 'https://api.instagram.com/v1/tags/zipcar/media/recent?client_id='.$instagramClientID; //api request (edit this to reflect tags)
$response = get_curl($api); //change request path to pull different photos
So I want to decode the json
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
...
So now I want to reformat the contents of said array into a particular json format (geojson) the code would be roughly this:
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
And then use json_encode to return it all into a nice json file to cache on the server.
My question...is how to I use the code above to loop through the json? The outer structure of the array/json is static but the interior needs to change.
In this case it's better to build a new data structure instead of replacing the existing one inline.
Example:
<?php
$instagrams = json_decode($response)->data;
$features = array();
foreach ( $instagrams as $instagram ) {
if ( !$instagram->location ) {
// Images aren't required to have a location and this one doesn't have one
// Now what?
continue; // Skip?
}
$features[] = array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(
$instagram->location->longitude,
$instagram->location->latitude
),
'type' => 'Point'
),
'properties' => array(
'longitude' => $instagram->location->longitude,
'latitude' => $instagram->location->latitude,
// Don't know where title comes from
'title' => null,
'user' => $instagram->user->username,
// No idea where id comes from since instagram's id seems to belong in instagram_id
'id' => null,
'image' => $instagram->images->standard_resolution->url,
// Assuming description maps to caption
'description' => $instagram->caption ? $instagram->caption->text : null,
'instagram_id' => $instagram->id,
)
);
}
$results = array(
'type' => 'FeatureCollection',
'features' => $features,
);
print_r($results);