Reading Array and Getting Variable Output - php

By default, Gravity Form merge tags for checkboxes output the value of the selected option. If they choices for a question are English, Spanish, and Other, and the user selects English, the merge tag outputs:
english
My end goal is to be able to customize a Gravity Form merge tag output for checkboxes to include all of the options, checkbox-like format, and the selected option (checkbox is checked).
Right now, I'm trying to at least be able to return all of the options. Using this function,
`
add_action( 'gform_pre_submission_3', 'pre_submission_handler' );
function pre_submission_handler( $form ) {
foreach($form['fields'] as &$field) {
if($field['id'] === 13) {
//$selectData['inputs'] = $field['inputs'];
$selectData['selections'] = $field['choices'];
$the_fields = $selectData;
foreach ($the_fields as $fields) {
print_r($fields);
}
}
}
I can get an output:
Array (
[0] => Array (
[text] => English
[value] => Language: English
[isSelected] =>
[price] =>
)
[1] => Array (
[text] => Spanish
[value] => Language: Spanish
[isSelected] =>
[price] =>
)
[2] => Array (
[text] => Other (specify)
[value] => Other
[isSelected] =>
[price] =>
)
)
I think that I'm going to need to get the [text] for each of the sub arrays into a new array. What's the syntax like to do that?
With the new array, I will be able to do a foreach loop, wrapping each element in HTML, using CSS to style the output like a checkbox.

As shorty:
$new_array = array_map(function($a){return $a['text'];},$fields);
;)

Related

array index changing into string [name] not number

I have form (display.php) that will get multiple selected option from user. Then this selected option will be formatted to another page (page.php). The problem occur when I try to display those multiple selected option. The array index are changing into string [name]!
Array ( [0] => 3204120006 [1] => 3204120011 [2] => 3204120010 [3] => 3204120009 )
Array ( [name] => BIRU ) Array ( [name] => BOJONG ) Array ( [name] => MAJAKERTA ) Array ( [name] => MAJALAYA )
Here the code of above display.
<?php
if (isset($_POST["desas"])) {
$ddes=$_POST["desas"];
print_r ($ddes);
foreach ( $ddes as $iddesa ) {
$namadesa=mysql_query("SELECT name FROM villages WHERE id='$iddesa' ");
if ($namadesa) {
$datadesa = mysql_fetch_assoc($namadesa);
print_r($datadesa);
}
} else
$datadesa="";
}
?>
My question is how to change ([name]=>BIRU),([name]=>BOJONG) into index ([0]=>BIRU),([1]=>BOJONG) etc on those array? or something missing in mysql fetch?
you can use array_values. reference: https://secure.php.net/manual/en/function.array-values.php
$datadesa = array_values(array_values);

PHP - Access an array using another array as the key

I'm creating a class that assists in building settings pages for WordPress plugins. The developer instantiates the class by passing in an array of settings. A basic example looks like:
Array
(
[textbox1] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[a_nice_dropdown] => Array
(
[title] => Select me
[type] => select
[section] => general
[desc] => The select description
[choices] => Array
(
[red] => Red
[blue] => Blue
[green] => Green
)
)
)
This works fine. My class builds the options page and the inputs have HTML that looks like:
<input id="textbox1" type="text" name="options_slug[textbox1]" value="">
When "Save Changes" is clicked, my class grabs all the options tied to "options_slug" and stores them in a single wp_options entry as a nice serialized array, making it easy to grab later.
The New Challenge
I have a new project which requires multiple nested "repeater" fields, similar to the way Advanced Custom Fields handles it. I've created a new field type, to handle this, which can support "subfields". An example config output (from error_log) looks like:
Array
(
[subfields_container] => Array
(
[title] => Subfields
[type] => subfields
[section] => general
[desc] => This is the subfields description text
[subfields] => Array
(
[textbox2] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[select1deep] => Array
(
[title] => Subfield Select
[type] => select
[choices] => Array
(
[1] => 1
[2] => 2
[3] => 3
)
[std] => 1
)
)
)
)
I've configured the HTML output so an input inside a "subfields" container now looks like:
<input id="textbox1" type="text" name="options_slug[subfields_container][textbox2]" value="">
The idea being that the end user can easily group fields: i.e.,
$options = get_option('options_slug');
foreach($options['subfield_container'] as $subfield) {
// etc...
}
The Problem
As I iterate through these multidimensional arrays, I need to continually update a $options variable at the current index so it can be saved to the DB. So where previously I was able to do:
$id = 'textbox1';
$options[$id] = $_POST['textbox1'];
Now I'm doing something like:
$id = array('subfields_container' => 'textbox2');
$options[$id] = $_POST['textbox2'];
But I get "illegal offset type" errors. Because I can't set an array property using another array.
I've considered just putting dashes in the ID's instead of creating a hierarchical array, something like:
<input id="textbox1" type="text" name="options_slug[subfields_container-textbox2]" value="">
But then I'll lose the ability to foreach over a specific part of the stored options.
The Question
What's the best way to dynamically set a value inside of a multidimensional array when the array is not fixed in structure?
Thank you
I'd suggest to just dynamically create a multi-leveled array:
$arr = array();
$arr['subfields_container']['textbox1'] = $_POST['textbox1'];
print_r($arr);
=>
Array
(
[subfields_container] => Array
(
[textbox1] => <POSTed value>
)
)
All of the non-existent keys will just be created on the fly, regardless of the number of nested levels you specify.
Update
Given that the user can arbitrarily specify any number of nesting levels as elucidated below, you probably want a recursive function that returns the values for all the elements of the current level, and calls itself to retrieve the values for any elements at the current level that contain sub elements.
Example:
function getNestedPostVars($config, $formName, $keys = array()) {
$output = [];
foreach ($config as $label => $fieldConfig) {
if (isset($config['subfields'])) {
$output[$label] = getNestedPostVars(
$config['subfields'],
$formName,
array_merge($keys, array($label))
);
continue;
}
$output[$label] = /* path to $_POST element using $keys/$label */ ;
}
return $output;
}

Getting a value of a PHP array

I have this array which I would like to get the individual values of each item:
This is the result of print_r($theme_option):
Array ( [side_bars] => Array ( [0] => Array ( [title] => Left Page Sidebar [sort] => 0 ) [1] => Array ( [title] => Right Page Sidebar [sort] => ) [2] => Array ( [title] => Left Blog Sidebar [sort] => ) [3] => Array ( [title] => Right Blog Sidebar [sort] => ) )
I can get at a single sidebar name by using:
$theme_option['side_bars'][0]['title'];
I tried to loop through and get the individual sidebars using this code but it doesn't return as expected.
global $theme_option;
if(isset($theme_option['side_bars']) && is_array($theme_option['side_bars'])){
foreach ($theme_option['side_bars'] as $key => $value) {
$theme_side_bars["$key"] = "$value";
}
}
What I ant to try and do is get the value of each "Sidebar" and place the "title" into a dropdown box.
Thanks
There is an array side_bars which contains an array with all the special infos.
With this code you should have an array with all titles stored in the variable $theme_side_bars.
global $theme_option;
$theme_side_bars = array();
if(isset($theme_option['side_bars']) && is_array($theme_option['side_bars'])){
foreach ($theme_option['side_bars'] as $index=>$arr) {
$theme_side_bars[] = $arr['title'];
}
}

jQuery post input with same names but in different arrays

I have various forms in a single page.
All the forms get submitted by the below jQuery function.
All is ok, but there is a specific form that has duplicated input names.
In fact in this form the inputs get cloned on request.
So for example, this form represents how many people attend an event.
The user can add as many people as he wants and adding details of each by filling the form.
The inputs get cloned on the fly and inserted inside the form.
The problem is that jQuery is sending them in the wrong way, like shown below, and my php code is not responding well. In fact it just sees one of the posted "people" instead that them all.
Example of jquery post:
protagonist_description zxcvvcbhcvbjfg
protagonist_description jfghjfghjh
protagonist_email
protagonist_email
protagonist_name zxcvzxcv
protagonist_name dfghdfgh
protagonist_phone
protagonist_phone
protagonist_role zxcvxzcv
protagonist_role hgfjgfhjhgh
protagonist_surname zcxvzxcv
protagonist_surname dfghd
protagonist_video
protagonist_video
protagonist_website
protagonist_website
Example of PHP response:
Array
(
[protagonist_name] => dfghdfgh
[protagonist_surname] => dfghd
[protagonist_role] => hgfjgfhjhgh
[protagonist_description] => jfghjfghjh
[protagonist_email] =>
[protagonist_phone] =>
[protagonist_website] =>
[protagonist_video] =>
)
As you see it just gets the last posted.
Here is my jQuery function:
$(".save").click(function() {
$.ajax({
type: 'POST',
data: $('form[name="wizard_form"]').serialize(),
success: function() {
$('#publish').modal('show');
}
});
});
Please note that all the cloned inputs are inside the same form.
I can only use one form. So please do not suggest using more cloned forms. It won't work for my code as it is.
I am looking for a way to correctly merge the inputs with the same name in specific arrays posted to the PHP code.
How to do that?
You first need to change your form inputs to be arrays by adding [] to the name like so:
<input name="protagonist_description[]" />
And then in your PHP it will look like this:
Array
(
[protagonist_name] => Array
(
[0] => zxcvzxcv,
[1] => dfghdfgh,
)
[protagonist_surname] => Array
(
[0] => zcxvzxcv,
[1] => dfghd,
)
[protagonist_role] => Array
(
[0] => zxcvxzcv,
[1] => hgfjgfhjhgh,
)
[protagonist_description] => Array
(
[0] => zxcvvcbhcvbjfg,
[1] => jfghjfghjh,
)
[protagonist_email] => Array
(
[0] => ,
[1] => ,
)
[protagonist_phone] => Array
(
[0] => ,
[1] => ,
)
[protagonist_website] => Array
(
[0] => ,
[1] => ,
)
[protagonist_video] => Array
(
[0] => ,
[1] => ,
)
)
At this point you can then loop through the values like this:
for ($i = 0, $max = count($_POST['protagonist_name']); $i < $max; $i++) {
$first_protagonist = array(
'protagonist_name' => $_POST['protagonist_name'][$i],
'protagonist_surname' => $_POST['protagonist_surname'][$i],
// ...
);
}
Per David's suggestion, here's the code for a foreach if you wish:
foreach ($_POST['protagonist_name'] as $key => $val) {
$first_protagonist = array(
'protagonist_name' => $val,
'protagonist_surname' => $_POST['protagonist_surname'][$key],
'protagonist_description' => $_POST['protagonist_description'][$key],
// ...
);
}
You need to add brackets to your input's name.
Example:
<input name="my_name[]" value="david" />
<input name="my_name[]" value="john" />
<input name="my_name[]" value="francis" />
$_POST['my_name'] will be an array containing all results.
Array
(
[my_name] => Array
(
[0] => david
[1] => john
[2] => francis
)
)
To handle arrays of input elements, in other words defined as having the same element name. If you define the name with two square brackets in the end it will be transformed to an array on the server side for php.
<input type='text' name='elmname[]' .....
<input type='text' name='elmname[]' .....
if you submit the form consisting these elements and then on the php side you will see that $_POST['elmname'] will be an array

Array manipulation to create a dropdown box cakephp

this is my problem
i,ve to create a dropdown list box from a table states('id','state_name') which is not my default model( which has many fields one of the field is 'state' in which i store states('id') .
so i used loadModel to populate the drop down box.
in my controller i used
$this->loadModel('State');
$this->set('states',$this->State->find('all'));
in the view side
$form->select('State_id',$states);
in the output the table name, the id and name are displaying.
when i printed $states using pr();
what i got was
Array
(
[0] => Array
(
[State] => Array
(
[id] => 1
[state_name] => state1
)
)
[1] => Array
(
[State] => Array
(
[id] => 2
[state_name] => state2
)
)
and so on
how to create an array like array(1=>state1, 2=>state2) from the above array
or is there any other way to create a dropdown listbox
kindly help
This is the way:
$fields = array('id','state_name');
$states = $this->State->find('list',array('fields'=>$fields));
$this->set(compact('states'));
or in one line:
$this->set('states',$this->State->find('list',array('fields'=>array('id','state_name'))));
The below code will create the array you wanted from the original array
$newstates = array();
foreach($states as $state) {
$state = $state['State']
$newstates[$state['id']] = $state['state_name'];
}
print_r($newstates);
Result:
Array
(
[1] => state1
[2] => state2
)

Categories