I have this code that gets me out some checkboxes with the watchdog severities:
/**
* Checkbox for errors, alerts, e.t.c
*/
foreach (watchdog_severity_levels() as $severity => $description) {
$key = 'severity_errors' . $severity;
$form['severity_errors'][$key] = array(
'#type' => 'checkbox',
'#title' => t('#description', array('#description' => drupal_ucfirst($description))),
'#default_value' => variable_get($key, array()),
);
return system_settings_form($form);
}
I set this $key in my code as:
$key = array_filter(variable_get($key,array()));
I think this set is wrong as the drupal gets me out error.
After that set of $key I call it with the following foreach statement could someone help me with that thing?
foreach ($key as $value) {
if ($value == 'warning') {
blablblablabla....
}
elseif ($value == 'notice') {
blablablbalbal....
}
}
Using your logic, you would store following keys severity_errors0, severity_errors1, severity_errors2, ... in the variable table because the $severity key of your foreach is just the index.
Wouldn't it be easier to store an array of selected severity levels as one entry in the variable table?
Here some example code which does the job for you:
// Retrieve store variable
$severity_levels = variable_get('severity_levels', array());
// Declare empty options array
$severity_options = array();
// Loop through each severity level and push to options array for form
foreach (watchdog_severity_levels() as $severity) {
$severity_options[$severity] = t('#description', array(
'#description' => drupal_ucfirst($severity),
));
}
// Generate checkbox list for given severity levels
$form['severity_levels'] = array(
'#type' => 'checkboxes',
'#options' => $severity_options,
'#default_value' => array_values($severity_levels),
);
return system_settings_form($form);
Now to retrieve the selected severity levels, you do something like this:
// Retrieve store variable
$severity_levels = variable_get('severity_levels', array());
foreach ($severity_levels as $level => $selected) {
if (!$selected) {
// Severity level is not selected
continue;
}
// Severity level is selected, do your logic here
// $level
}
You need to add some debugging to figure out where exactly it's going wrong. Would recommend using dpm() to inspect the code at some of the key stages like 1) after building the form, 2) when you assign the array to $key and 3) before starting the final foreach loop so you can pinpoint where it's going wrong and address it.
Related
I'm attempting to update a nested array in php. However, my updates have no effect. Here's the relevant code:
foreach($form["fields"] as $field){
Populate Checkbox Fields
if($field['type'] == 'checkbox'){
$inputs = $field['inputs'];
$count = '0';
foreach($inputs as $input){
if(($user_meta[$input['id']] !== '') && (isset($user_meta[$input['id']]))){
$select = true;
}
else{
$select = false;
}
$field['choices'][$count] = array( 'text' => $field['choices'][$count]['text'], 'value' => $field['choices'][$count]['value'] , 'isSelected' => $select );
$count = $count + '1';
}
}
}
I've tried a few different workarounds after searching for this error, but none of them seem effective. I'm grateful for any help anyone can offer.
Just use a reference & for $field with your existing code:
foreach($form['fields'] as &$field){
Alternately, use the key and modify the main array:
foreach($form['fields'] as $key => $field){
// later in the code
$form['fields'][$key]['choices'][$count] = array( /* ... */ );
I need help to change the index of an array.
I have this array:
$items = array('items' => array(
0 => array(
'item_id' => 1,
'item_amount' => 100,
),
1 => array(),
));
Now I want to remove the index, based on the value of item_id, but I don't know how to do this.
I've tried to do it as follows, but doesn't work.
foreach($items['items'] as $key) {
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($removeIndex);
}
}
How can I do this?
You need to use unset like this:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]['item_id']); // specify path to that entry
}
}
See it run on eval.in.
To unset something in your nested array structure, you need to act on that array itself. unset($removeIndex) does not change the array, because that is a boolean value.
The extra if is there for the case when you don't have an item_id in some sub-array: in that case that iteration of the loop is skipped.
Removing the entire "row"
If your aim is to also remove the sub-array to which the item_id belongs (so including the item_amount and any other value in that sub-array), then just shorten the "path" in the unset statement:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]); // specify path to that entry
}
}
See it run on eval.in.
You need to call unset($items['items'][0]). For your case it will be something like this:
$id = 1;
$keyToRemove = false;
foreach ($items['items'] as $key => $value) {
if ($value['item_id'] == $id) {
$keyToRemove = $key;
break;
};
}
if ($keyToRemove) {
unset($items['items'][$keyToRemove]);
}
If you want to remove the specific entry 'item_id' in the $items array, you have to refer to it and use both keys, like in:
foreach($items['items'] as $key => $val) {
if (!isset($val['item_id'])) continue;
$removeIndex = $val['item_id'] == 1;
if($removeIndex)
unset($items['items'][$key]);
}
If you downvote, please state why you think this answer is not appropriate.
I keep getting the error:
PHP Notice: Undefined offset: 1 in /home/mydomain/mydomain.com/admin/model/tool/export_xls.php on line 150
I've looked at the other similar posts but none of those resolutions work on my code. I don't see any numbers related to the array, and I've double checked for missing closing } . I asked the code developer and all he did was get it to stop displaying the error, but it still shows up (several thousand times) in my error log. line 150 is the blank line above the code
"//Get all options values to each option"
Code:
public function get_all_options()
{
$this->load->model('catalog/option');
$all_options = $this->model_catalog_option->getOptions();
$options_final = array();
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']] = array(
'option_id' => $op['option_id'],
'option_name' => $op['name'],
'option_values' => array()
);
}
//Get all options values to each option
foreach ($options_final as $option_name => $op) {
$option_values = $this->model_catalog_option->getOptionValues($op['option_id']);
//Format option values
$option_values_final = array();
foreach ($option_values as $key => $op) {
$option_values_final[$op['name']] = $op['option_value_id'];
}
$options_final[$option_name]['option_values'] = $option_values_final;
}
return $options_final;
}
This is because you are accessing an array which index is not set . try something like this
//Format options
foreach ($all_options as $key => $op) {
$options_final[$op['name'].'_'.$op['type']]
= array(
'option_id' =>isset($op['option_id']) ?
:$op['option_id']:null,
'option_name' => isset($op['option_name'])
? :$op['option_name']:null,
'option_values' => array()
);
}
I need to update values I have in a PHP array. It seems that the values are not updating whenever I assign new values to a certain item. Here's my code:
$actions = array(
array('action' => 'Action1', 'value' => '0'),
array('action' => 'Action2', 'value' => '0'),
);
foreach($actions as $item){
if($item['action'] == 'Action1'){
$item['value'] = 20;
}
}
After doing this foreach loop, the array remains as is. With all values having the 0 value.
When you us a for each loop you are not updating the original array. You are just updating the $item var in the scope of the loop
You need to pass by reference rather than value
foreach ($actions as &$item) {
}
Notice the & before the $item this will cause your changes to update the original array.
Try This
foreach($actions as $key => $val){
if($val['action'] == 'Action1'){
$actions[$key]['value'] = 20;
}
}
you are modifying a copy of the variable, what you want is one of the following:
foreach($actions as &$item){ //<== add "&" reference to the $item that now when ever you change it the actions will change
if($item['action'] == 'Action1'){
$item['value'] = 20;
}
}
OR
foreach($actions as $key => $item){
if($item['action'] == 'Action1'){
$actions[$key]['value'] = 20; // directly access $action and modify the value
}
}
Besides the answers above, you may also try this:
foreach(array_keys($actions) as $key){
$item = &$actions[$key];
if($item['action'] == 'Action1'){
$item['value'] = 20;
}
}
I remember the the method like
foreach($actions as &$item)
may cause some wired problem under certain circumstance. I've encountered once in Drupal but cannot remember where.
Here is example how my array should look like:
$library = array(
'book' => array(
array(
'authorFirst' => 'Mark',
'authorLast' => 'Twain',
'title' => 'The Innocents Abroad'
),
array(
'authorFirst' => 'Charles',
'authorLast' => 'Dickens',
'title' => 'Oliver Twist'
)
)
);
When I get results from oracle database:
$row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS);
But when I execute my code I only get one row.
For example: <books><book></book><name></name></books>
But I want all rows to be shown in xml.
EDIT:
This is my class for converting array to xml:
public static function toXml($data, $rootNodeName = 'data', &$xml=null)
{
// turn off compatibility mode as simple xml throws a wobbly if you don't.
if (ini_get('zend.ze1_compatibility_mode') == 1)
{
ini_set ('zend.ze1_compatibility_mode', 0);
}
if (is_null($xml))
{
$xml = simplexml_load_string("<".key($data)."/>");
}
// loop through the data passed in.
foreach($data as $key => $value)
{
// if numeric key, assume array of rootNodeName elements
if (is_numeric($key))
{
$key = $rootNodeName;
}
// delete any char not allowed in XML element names
$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
// if there is another array found recrusively call this function
if (is_array($value))
{
// create a new node unless this is an array of elements
$node = ArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml;
// recrusive call - pass $key as the new rootNodeName
ArrayToXML::toXml($value, $key, $node);
}
else
{
// add single node.
$value = htmlentities($value);
$xml->addChild($key,$value);
}
}
// pass back as string. or simple xml object if you want!
return $xml->asXML();
}
// determine if a variable is an associative array
public static function isAssoc( $array ) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
}
?>
Now with below responde I have tried problem is I get following output: <book>...</book> tags after each row.. then I tried 3 dimensional array now I get: <book><book>...</book></book> on the proper place but I have 2 of them.
This is the line where I have determine which is root on that array and that's why I get this output. But don't know how to change it : $xml = simplexml_load_string("<".key($data)."/>");
Thank you.
oci_fetch_array() will always return a single row, you need to call it until there are no more rows to fetch in order to get all of them:
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS))
{
$library['book'][] = $row;
}