function dump_results($a) { print_r($a); is_numeric_array($a) ? printf("%s\n", 'This array is numeric') : printf("%s\n", 'This array is not numeric'); is_assoc_array($a) ? printf("%s\n", 'This array is associative') : printf("%s\n", 'This array is not associative'); print "\n\n"; }
function XML2Array($xml, $recursive = false) { if (!$recursive) { $array = simplexml_load_string($xml); } else { $array = $xml; } $newArray = array(); $array = (array) $array; foreach ($array as $key => $value) { //echo $key."\n"; //echo "---\n"; $value = (array) $value; if (is_string($value)) { $newArray[strtolower($key)] = trim($value); } else { if (!is_assoc_array($value) && isset($value[0]) && sizeof($value) == 1) { $newArray[strtolower($key)] = trim($value[0]); } else { //echo "AAA".$key."\n"; //print_r($value); $newArray[strtolower($key)] = XML2Array($value, true); } } } return $newArray; }
/** * Test is_numeric_array and is_assoc_array */ function test_is_functions() { $this->assertTrue(is_numeric_array(array())); $this->assertTrue(is_assoc_array(array())); $data = array('a', 'b', 'c'); $this->assertTrue(is_numeric_array($data)); $this->assertTrue(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertFalse(is_assoc_array($data, true)); $data = array(1, 2, 3); $this->assertTrue(is_numeric_array($data)); $this->assertTrue(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertFalse(is_assoc_array($data, true)); $data = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc'); $this->assertFalse(is_numeric_array($data)); $this->assertTrue(is_assoc_array($data)); $data = array('a', 'b' => 'bb', 'c' => 'cc', 'd' => 'dd'); $this->assertTrue(is_numeric_array($data)); $this->assertFalse(is_numeric_array($data, true)); $this->assertFalse(is_assoc_array($data)); $this->assertTrue(is_assoc_array($data, true)); $data = array('a' => 'aa', 'b', 'c'); $this->assertFalse(is_numeric_array($data)); $this->assertFalse(is_numeric_array($data, true)); $this->assertTrue(is_assoc_array($data)); $this->assertTrue(is_assoc_array($data, true)); }
function get_modules_list($size = 10, $offset = 0) { $modules = scandir(ABSPATH . '/' . MODULES); $res = array(); $i = $o = 0; foreach ($modules as $dir) { $path = ABSPATH . '/' . MODULES . '/' . $dir; if (is_dir($path) && file_exists($path . '/main.php')) { $o++; if ($o > $offset) { $i++; if ($i > $size) { break; } $custom = array('name' => $dir, 'description' => '', 'version' => '', 'author' => 'Unnamed', 'url' => ''); if (file_exists($path . '/info.json')) { $content = read_json($path . '/info.json', true); if ($content && is_assoc_array($content)) { $custom = set_merge($custom, $content, false, array('clear' => true)); } } $custom['path'] = $dir; $res[] = $custom; } } } return $res; }
/** * Метод ищет в строке подстроки, удовлетворяющие шаблону и заменяет их по очереди на подстановки, * переданные в виде массива. Поиск идёт по регулярному выражению! * * @param string $pattern - шаблон * @param string $text - текст * @param array $tokens - массив подстановок * @return string */ public static function replace($pattern, $text, array $tokens) { self::$inst = self::$inst ? self::$inst : new PregReplaceCyclic(); self::$inst->tokens = check_condition($tokens, 'Не переданы элементы для замены'); if (is_assoc_array($tokens)) { raise_error('Недопустим ассоциативный массив подстановок. Передан: ' . array_to_string($tokens, true)); } self::$inst->idx = 0; self::$inst->count = count($tokens); return preg_replace_callback($pattern, array(self::$inst, '_replace'), $text); }
/** * The function is used to set data, the field value could be an array, then * the full value will be assigned to data array * * @param mixed $field the name of the field/a list of data array * @param mixed $value the field value * * @return Object */ public function setData($field, $value = null) { if (is_assoc_array($field)) { $this->data = $field; } else { if (is_string($field)) { $this->data[$field] = $value; } else { // do nothing here throw new \RuntimeException("Invalid field value assigned (must be string or associated array)"); } } return $this; }
/** * Add a new record to the database * If it is an associative array, you must use get_empty_record() * to ensure that everything is empty EXCEPT those in $row * * TODO: After it gets added, how do we know without doing a search? * @param array $row an array of rows * @param bool $fillempty do we populate the array with empty values? (using the header_info) * @return bool true on added, false on failure (dbase_add_record() result) */ public function add($row, $fillempty = true) { $this->add_info = array(); if (is_assoc_array($row)) { if ($fillempty) { $new_row = $this->get_empty_record(); $this->add_info['invalid_key_count'] = 0; //copy all values to the $new_row foreach ($new_row as $k => $v) { if (isset($row[$k])) { $new_row[$k] = $row[$k]; } else { $this->add_info['invalid_key_count']++; } } //ok now $row should ONLY contain valid data $row = $new_row; } //we can't add a deleted row, therefore: unset($row["deleted"]); // drop the field $this->add_info['associative_row'] = $row; // then convert to numeric to store: $rarr = array(); foreach ($row as $i => $vl) { $rarr[] = $vl; } $row = $rarr; $this->add_info['row'] = $row; } //end if an associative array //first convert record to a normal array (if it is associative) $this->add_info['added'] = dbase_add_record($this->db, $row); return $this->add_info['added']; }
/** * Find one or more records by providing a part of the SQL query. * * \param $class Class name * * \param $just_one_result * Whether to return just one instance (or null) or an array of instances * * \param $sql The constraints of the SQL query * \param $values Array with placeholder values * * \param $connection AnewtDatabaseConnection instance */ protected static final function _db_find_by_sql($class, $just_one_result = false, $sql = null, $values = array(), $connection) { assert('is_string($class)'); assert('is_bool($just_one_result)'); assert('is_null($sql) || is_string($sql) || is_assoc_array($sql)'); assert('is_array($values)'); assert('$connection instanceof AnewtDatabaseConnection'); /* Table alias. * * Several possibilities exist: * - no alias, * - alias provided explicitly, or * - not specified but still needed. */ $table_alias = null; if (is_assoc_array($sql)) { /* Table alias might be provided explicitly */ $table_alias = array_get_default($sql, 'table-alias', null); /* If JOINs are used, a table alias must be used for all columns in * the SELECT clause to avoid ambiguous column names if the same * column names are used in one of the JOINed tables. If no * table-alias is provided explicitly, the table name is reused. */ if (is_null($table_alias) && array_key_exists('join', $sql)) { $table_alias = call_user_func(array($class, 'db_table')); } } /* Standard query parts */ $sql_select = AnewtAutoRecord::_db_sql_select($class, $table_alias, $connection); $sql_from = AnewtAutoRecord::_db_sql_from($class, $table_alias, $connection); $sql_order_by = AnewtAutoRecord::_db_sql_order_by($class, $table_alias, $connection); /* Build the SQL query. * * There are three possibilities for the $sql parameter: * 1. null * 2. a string * 3. an associative array */ if (is_null($sql)) { /* No SQL: find all records */ $sql_order_by_full = is_null($sql_order_by) ? '' : sprintf('ORDER BY %s', $sql_order_by); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_order_by_full); } elseif (is_string($sql)) { /* SQL string */ $sql_with_values = $connection->create_sql_template($sql)->fillv($values); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_with_values); } else { /* Associative array with SQL */ $sql_parts = array(); /* SELECT and possible additions */ $sql_select_addition = array_get_default($sql, 'select', null); if ($sql_select_addition) { $sql_select = sprintf('%s, %s', $sql_select, $sql_select_addition); } /* WHERE */ $sql_where = array_get_default($sql, 'where', null); if (!is_null($sql_where)) { $sql_parts[] = sprintf('WHERE %s', $sql_where); } /* JOIN */ $sql_join = array_get_default($sql, 'join', null); if (!is_null($sql_join)) { $sql_from = sprintf('%s %s', $sql_from, $sql_join); } /* ORDER BY */ $sql_order_by = array_get_default($sql, 'order-by', $sql_order_by); if (!is_null($sql_order_by)) { $sql_parts[] = sprintf('ORDER BY %s', $sql_order_by); } /* LIMIT. Note that "optimizing" this depending on the value of * $just_one_result is impossible since it may contain a placeholder * string and not a literal value. We take care of $just_one_result * when fetching the result rows. */ $sql_limit = array_get_default($sql, 'limit', null); if (!is_null($sql_limit)) { $sql_parts[] = sprintf('LIMIT %s', $sql_limit); } /* OFFSET */ $sql_offset = array_get_default($sql, 'offset', null); if (!is_null($sql_offset)) { $sql_parts[] = sprintf('OFFSET %s', $sql_offset); } /* Combine */ $sql_parts_combined = $connection->create_sql_template(join(' ', $sql_parts))->fillv($values); $sql_full = $connection->create_sql_template('SELECT ?raw? FROM ?raw? ?raw?;')->fill($sql_select, $sql_from, $sql_parts_combined); } /* Fetch resulting row(s) and create AnewtAutoRecord instances. * * The generated SQL query may contain placeholders (e.g. the string * '?int?' could be somewhere in a value), but those must not be parsed * by AnewtDatabaseSQLTemplate. Since the generated SQL is already fully * escaped, it is passed as a single value for a ?raw? query. See * bug:502916 for more information. */ if ($just_one_result) { $row = $connection->prepare_execute_fetch_one('?raw?', $sql_full); if (!$row) { return null; } return AnewtAutoRecord::_db_object_from_array($class, $row); } else { $rows = $connection->prepare_execute_fetch_all('?raw?', $sql_full); return AnewtAutoRecord::_db_objects_from_arrays($class, $rows); } }
function render($option = array(), $value = null) { $fieldname = $option['param_name']; $fieldid = sanitize_html_class($fieldname); $css = isset($option['class']) && '' != $option['class'] ? " " . (is_array($option['class']) ? @implode(" ", $option['class']) : $option['class']) : ""; //sanitize_html_class($fieldname); $dependency = create_dependency_param($option); $sidebars = krypton_get_registered_sidebars(); $compile = "<select id=\"" . $fieldid . "\" class=\"param_value select-option" . $css . "\" name=\"" . $fieldname . "\"" . $dependency . ">"; if (is_array($sidebars) && count($sidebars)) { foreach ($sidebars as $key => $label) { if (is_numeric($key) && !is_assoc_array($sidebars)) { $key = $label; } $compile .= "<option value=\"" . $key . "\"" . ($key == $value && '' != $value ? " selected=\"selected\"" : "") . ">" . $label . "</option>"; } } $compile .= "</select>"; return $compile; }
function json_serialize($data) { if (is_assoc_array($data)) { $json = array(); foreach ($data as $key => $value) { array_push($json, '"' . $key . '": ' . json_serialize($value)); } return '{' . implode(', ', $json) . '}'; } if (is_array($data)) { $json = array(); foreach ($data as $value) { array_push($json, json_serialize($value)); } return '[' . implode(', ', $json) . ']'; } if (is_int($data) || is_float($data)) { return $data; } if (is_bool($data)) { return $data ? 'true' : 'false'; } return '"' . encode_for_json($data) . '"'; }
function string_values($arr, $var = null, $par = null) { $str = ''; $mode = is_assoc_array($arr) && $par == null ? true : false; if ($mode) { $par = $var; } $custom = array('separ' => ',', 'empty' => 'NULL', 'middle' => '=', 'body' => "'", 'json' => false); $custom = set_merge($custom, $par); $arr = take_good_array($arr, true, $custom['json']); if (!$mode) { $var = take_good_array($var, false, $custom['json']); if (count($arr) == 1 && count($var) > 1) { $var = array(json_val_encode($var)); } } $L = get_last_key($arr); $i = 1; if (!$mode && $var) { $B = count($arr) < count($var) ? count($arr) : count($var); } else { $B = count($arr); } foreach ($arr as $key => $item) { if ($i <= $B) { $item1 = $item2 = null; if ($mode) { $item1 = $key; $item2 = $item; } elseif (isset($var[$key])) { $item1 = $item; $item2 = $var[$key]; } if (is_jsoned($item1)) { $item1 = json_val_encode($item1); } if (is_jsoned($item2)) { $item2 = json_val_encode($item2); } $str .= "{$item1}{$custom['middle']}{$custom['body']}{$item2}{$custom['body']}"; if ($key != $L && $i < $B) { $str .= $custom['separ']; } $i++; } } return $str; }
private function custom_where($param) { $cond = ''; if (is_array($param)) { $i = 0; if (is_assoc_array($param)) { $param = array($param); } $custom = array('log' => 'AND', 'relation' => '=', 'param' => '', 'value' => ''); foreach ($param as $sub_cond) { if (isset($sub_cond['param'])) { $temp = set_merge($custom, $sub_cond); $temp['value'] = $this->escape_string($temp['value']); if ($i == 0) { $cond = ' WHERE '; } if ($i > 0 && $temp['log']) { $cond .= " {$temp['log']} "; } if ($i == 0 || $temp['log']) { $cond .= "{$temp['param']} {$temp['relation']} '{$temp['value']}'"; } $i++; } } } else { if ($param) { $cond = preg_match('/^(WHERE)/i', $param) ? $param : "WHERE {$param}"; } } return $cond; }
/** * Load configuration data from a ini file. * * If the ini file contains sections, the name of the configuration settings * will be the section name and the setting name with a hyphen in between, * e.g. the <code>hostname=...</code> setting inside * a <code>[database]</code> setting can be retrieved using * <code>AnewtConfig::get('database-hostname')</code>. * * \param $filename * The filename of the ini file. */ public static function load_ini_file($filename) { assert('is_string($filename);'); if (!is_readable($filename)) { throw new Exception('The ini file does not exists or is not readable.'); } $parsed = parse_ini_file($filename, true); if ($parsed === false) { throw new Exception('The ini file could not be parsed.'); } $config = array(); foreach ($parsed as $name => $value) { /* The value can be either a string (for top level ini settings), or * an array (for ini settings in sections) */ if (is_string($value)) { $config[$name] = $value; } elseif (is_assoc_array($value)) { $section = $name; foreach ($value as $name => $value) { $key = sprintf('%s-%s', $section, $name); $config[$key] = $value; } } else { assert('false; // not reached;'); } } /* Cast integer and boolean values to the correct type */ foreach ($config as $name => &$value) { if (preg_match('/^-?[0-9]+$/', $value)) { $value = (int) $value; } elseif (preg_match('/^(1|true|yes|on)$/', $value)) { $value = true; } elseif (preg_match('/^(0|false|no|off)$/', $value)) { $value = false; } } AnewtConfig::seed($config); }
function array_to_string(array $array, $assoc = false) { $assoc = $assoc || is_assoc_array($array); $result = array(); foreach ($array as $key => $value) { $result[] = ($assoc ? "{$key}=>" : '') . (is_array($value) ? array_to_string($value, false) : var_export($value, true)); } return '[' . implode(', ', $result) . ']'; }
/** * Create a new record from the parent Model and new related records with it. * * @param array $attributes * @param array $relations * @return \Vinelab\NeoEloquent\Eloquent\Model */ public function createWith(array $attributes, array $relations) { // Collect the model attributes and label in the form of ['label' => $label, 'attributes' => $attributes] // as expected by the Query Builder. $model = ['label' => $this->model->getTable(), 'attributes' => $attributes]; /** * Collect the related models in the following for as expected by the Query Builder: * * [ * 'label' => ['Permission'], * 'relation' => [ * 'name' => 'photos', * 'type' => 'PHOTO', * 'direction' => 'out', * ], * 'values' => [ * // A mix of models and attributes, doesn't matter really.. * ['url' => '', 'caption' => ''], * ['url' => '', 'caption' => ''] * ] * ] */ $related = []; foreach ($relations as $relation => $values) { $name = $relation; // Get the relation by calling the model's relationship function. if (!method_exists($this->model, $relation)) { throw new QueryException("The relation method {$relation}() does not exist on " . get_class($this->model)); } $relationship = $this->model->{$relation}(); // Bring the model from the relationship. $relatedModel = $relationship->getRelated(); // We will first check to see what the dev have passed as values // so that we make sure that we have an array moving forward // In the case of a model Id or an associative array or a Model instance it means that // this is probably a One-To-One relationship or the dev decided not to add // multiple records as relations so we'll wrap it up in an array. if (!is_array($values) or is_assoc_array($values) or $values instanceof Model) { $values = [$values]; } $label = $relationship->getRelated()->getTable(); $direction = $relationship->getEdgeDirection(); $type = $relationship->getRelationType(); // Hold the models that we need to attach $attach = []; // Hold the models that we need to create $create = []; // Separate the models that needs to be attached from the ones that needs // to be created. foreach ($values as $value) { // If this is a Model then the $exists property will indicate what we need // so we'll add its id to be attached. if ($value instanceof Model and $value->exists === true) { $attach[] = $value->getKey(); } elseif ($value instanceof Collection) { $attach = array_merge($attach, $value->lists('id')); } elseif (!is_array($value) and !$value instanceof Model) { $attach[] = intval($value); } else { $create[] = $this->prepareForCreation($relatedModel, $value); } } $relation = compact('name', 'type', 'direction'); $related[] = compact('relation', 'label', 'create', 'attach'); } $result = $this->query->createWith($model, $related); $models = $this->resultsToModels($this->model->getConnectionName(), $result); return !empty($models) ? reset($models) : null; }
/** * Fill the SQL template using the values passed as a single parameter. * * This method will check all values for correctness to avoid nasty SQL * injection vulnerabilities. * * \param $values * Array with values to use for substitution. For positional placeholders * this should be a numeric array. For named placeholders an associative * array or AnewtContainer instance should be passed. * * \return * The query containing all values, quoted correctly. * * \see AnewtDatabaseSQLTemplate::fill */ public function fillv($values = null) { $n_placeholders = count($this->placeholders); $escaped_values = array(); /* I. Named mode */ if ($this->named_mode) { /* Sanity checks */ $values_is_container = $values instanceof AnewtContainer; if (!is_assoc_array($values) && !$values_is_container) { throw new AnewtDatabaseQueryException('SQL templates in named mode require a single associative array or AnewtContainer instance when filled.'); } /* Fill the placeholders */ for ($i = 0; $i < $n_placeholders; $i++) { list($field_name, $field_type, $multiple) = $this->placeholders[$i]; if ($values_is_container) { $value = $values->get($field_name); } else { if (!array_key_exists($field_name, $values)) { throw new AnewtDatabaseQueryException('No value specified for field "%s".', $field_name); } $value = $values[$field_name]; } /* Multiple values */ if ($multiple) { if (!is_numeric_array($value)) { throw new AnewtDatabaseQueryException('Value for field "%s[]:%s" is not a numeric array.', $field_type, $field_name); } $escaped_values[] = $this->escape_field_array($field_type, $value); } else { $escaped_values[] = $this->escape_field($field_type, $value); } } } else { /* Sanity checks */ if (!is_numeric_array($values)) { throw new AnewtDatabaseQueryException('SQL templates in positional mode can only be filled using a numeric array'); } $n_values = count($values); if ($n_placeholders != $n_values) { throw new AnewtDatabaseQueryException('Expected %d placeholder values, but %d values were provided.', $n_placeholders, $n_values); } /* Fill the placeholders */ foreach ($this->placeholders as $placeholder) { list($field_name, $field_type, $multiple) = $placeholder; $value = array_shift($values); /* Multiple values */ if ($multiple) { if (!is_numeric_array($value)) { throw new AnewtDatabaseQueryException('Value for field "%s[]" is not a numeric array.', $field_type); } $escaped_values[] = $this->escape_field_array($field_type, $value); } else { $escaped_values[] = $this->escape_field($field_type, $value); } } } /* Now that all supplied values are validated and escaped properly, we * can easily substitute them into the query template. The %s * placeholders were already prepared during initial parsing. */ $query = vsprintf($this->sql, $escaped_values); return $query; }
/** * \protected * * Fetch default value from the row data, based on the cell renderer id. * This method is used internally to fetch the cell data from the row data * object. Both associative arrays and Container objects are handled. Which * value is retrieved depends on the <code>id</code> of the cell renderer; * if you did not instantiate an AnewtGridCellRenderer yourself, this is * will be the same as the column <code>id</code>. * * Custom AnewtGridCellRenderer subclasses may use this method as * a convenience method to get data from the row object prior to further * processing or formatting. * * \param $data * Row data * * \return * Value extracted from row data, based on the <code>id</code> */ function fetch_value_from_data($data) { /* Handle arrays, */ if (is_assoc_array($data)) { $value = array_get_default($data, $this->id, null); } elseif ($data instanceof Container) { $value = $data->getdefault($this->id, null); } else { trigger_error('AnewtGridCellRenderer::render_cell(): This cell renderer can only render associative arrays and Container objects.', E_USER_ERROR); } return $value; }
/** * 更新记录 * * $adapter->update('users', array('passwd' => 'abc'), 'id = ?', 1); * $adapter->update('users', array('passwd' => 'abc'), array('id = ?', 1)); * $adapter->update('table', array('passwd' => 'abc'), 'id = :id', array(':id' => 1)); * $adapter->update('table', array('passwd' => 'abc'), 'id = :id', 1); * * @param string $table * @param array $row * @param mixed $where * @param mixed $bind * @access public * @return integer */ public function update($table, array $row, $where, $bind = null) { // 返回prepare后的结果 $return_prepare = false; // 先解析where if (is_array($where)) { $return_prepare = (bool) $bind; list($where, $where_bind) = call_user_func_array(array($this, 'parsePlaceHolder'), $where); } else { $args = func_get_args(); list($where, $where_bind) = call_user_func_array(array($this, 'parsePlaceHolder'), array_slice($args, 2)); } //检查place holder类型 $holder = null; if ($where_bind and !is_assoc_array($where_bind)) { $holder = '?'; } $set = $bind = array(); foreach ($row as $col => $val) { if ($val instanceof Expr) { $set[] = $this->qcol($col) . ' = ' . $val; continue; } $holder_here = $holder ?: ':' . $col; $set[] = $this->qcol($col) . ' = ' . $holder_here; if ($holder_here == '?') { $bind[] = $val; } else { $bind[$holder_here] = $val; } } $bind = array_merge($bind, $where_bind); $sql = sprintf('UPDATE %s SET %s', $this->qtab($table), implode(',', $set)); if ($where) { $sql .= ' WHERE ' . $where; } if (!($sth = $this->prepare($sql))) { return false; } if ($return_prepare) { return $sth; } if (!$this->execute($sth, $bind)) { return false; } if ($affected = $sth->rowCount()) { fire_event($this, UPDATE_EVENT, $this, $table, $affected); } return $affected; }
public function count() { if (is_assoc_array($this->data)) { return 1; } else { return count($this->data); } }
public function testIsAssocArray() { $this->assertTrue(is_assoc_array(['test' => 1, 'testing' => 2, 0 => '22'])); $this->assertFalse(is_assoc_array(['test', 'testing', '22'])); }
add_action(array('code' => 'admin_recaptcha_settings', 'rule' => 'admin_settings', 'category' => 'admin', 'auto' => 'settings', 'zone' => 'settings_secure', 'priority' => 100, 'function' => function () { $keys = get_option('admin_recaptcha_keys'); ?> <hr /> <h3>Настройки Google ReCaptcha</h3> <div class="row"> <div class="field form-group col-lg-4"> <label>Публичный ключ (Public key)</label> <input type="text" name="recaptcha_key[]" class="form-control data-control" value="<?php echo $keys[0]; ?> "> </div> </div> <div class="row"> <div class="field form-group col-lg-4"> <label>Приватный ключ (Private key)</label> <input type="text" name="recaptcha_key[]" class="form-control data-control" value="<?php echo $keys[1]; ?> "> </div> </div> <?php })); add_action(array('code' => 'check_admin_recaptcha_settings', 'rule' => 'admin_settings', 'category' => 'admin', 'zone' => 'settings_checking', 'priority' => 100, 'function' => function ($res) { if (isset($res['recaptcha_key']) && count($res['recaptcha_key']) == 2 && !is_assoc_array($res['recaptcha_key'])) { return update_option('admin_recaptcha_keys', $res['recaptcha_key']); } return false; }));
/** * \protected * * Create a new XHTML element. * * This constructor accepts a variable number of arguments. Each argument * is appended as a child node, but the last argument is handled * differently. If the last argument is an associative array, its values are * used as attribute names and values. If it's not an associative array, it * is treated just as the other arguments and appended as a child node. * * The AnewtXHTMLElement class is abstract and cannot be instantiated * directly. Use one of its descendants instead (all XHTML element classes * extend AnewtXHTMLElement); there is one class for each XHTML element in * the HTML specification. * * \param $children * One or more child nodes (optional). * * \param $attributes * Associative array with element attributes (optional). */ function __construct($children = null, $attributes = null) { assert('!is_null($this->node_name); // node name must be specified'); parent::__construct($this->node_name); $num_args = func_num_args(); if ($num_args == 0) { return; } $args = func_get_args(); /* Use last element for attributes, but only if it's an associative * array. */ if (is_assoc_array($args[$num_args - 1])) { $attributes = array_pop($args); $this->set_attributes($attributes); } /* Add additional arguments as child nodes. */ $this->append_children($args); }
/** * Return an HTML select tag containing a list of options * NOTE: The name can be an object property like "user->name" * * @param String $name the field name (required) * @param Array $options the options as a label list or label=>value pairs * @param String $selected the selected option value or label (optional) * @param Array $attrs the select tag's attributes (optional) * @return String the HTML select tag containing a list of options */ public static function select($name, $options, $selected = NULL, $attrs = array()) { if (is_null($selected)) { $selected = self::object_value_for($name); } $attrs['id'] = self::css_id_for($name, $attrs); $attrs['name'] = h($name); $html = '<select ' . self::attrs($attrs) . ">\n"; $is_assoc = is_assoc_array($options); foreach ($options as $label => $value) { if (!$is_assoc) { $label = $value; } $choose = $value === $selected || $label === $selected ? ' selected="selected"' : NULL; $html .= "<option value=\"{$value}\"{$choose}>{$label}</option>\n"; } return $html . "</select>\n"; }