function generate_gives_to($group_list, $attempt = 0) { $recipients = []; $givesto = []; $attempt += 1; foreach ($group_list as $k1 => $group) { $possible_recipients = array_merge(array_slice($group_list, 0, $k1), array_slice($group_list, $k1 + 1)); $possible_recipients = array_diff(flatten($possible_recipients), $recipients); foreach ($group as $k2 => $person) { if (empty($possible_recipients)) { if ($attempt < 10) { return generate_gives_to($group_list, $attempt); } else { echo " - INCOMPLETE SOLUTION - "; } } $k = array_rand($possible_recipients); $givesto[$person] = $possible_recipients[$k]; $recipients[] = $possible_recipients[$k]; unset($possible_recipients[$k]); } } fancy_print($givesto); return $givesto; }
function split_definitions($defs) { if (is_array($defs)) { return flatten(array_map("split_definitions", $defs)); } return array_map("trim", preg_split("/[,;\n]/", $defs)); }
function test_variadic() { $result = flatten([[1, 2], [3, 4]], [[5, 6]]); $expect = [1, 2, 3, 4, 5, 6]; $actual = iterator_to_array($result, false); $this->assertEquals($expect, $actual); }
function compile_node($options) { $idt1 = $options['indent'] . TAB; $idt2 = $options['indent'] = $idt1 . TAB; $code = $this->tab . 'switch (' . ($this->subject ? $this->subject->compile($options, LEVEL_PAREN) : 'false') . ") {\n"; foreach ($this->cases as $i => $case) { list($conditions, $block) = $case; foreach (flatten(array($conditions)) as $cond) { if (!$this->subject) { $cond = $cond->invert(); } $code .= $idt1 . 'case ' . $cond->compile($options, LEVEL_PAREN) . ":\n"; } if ($body = $block->compile($options, LEVEL_TOP)) { $code .= $body . "\n"; } if ($i === count($this->cases) - 1 && !$this->otherwise) { break; } $expr = $this->last_non_comment($block->expressions); if ($expr instanceof yy_Return || $expr instanceof yy_Literal && $expr->jumps() && '' . $expr->value !== 'debugger') { continue; } $code .= $idt2 . "break;\n"; } if ($this->otherwise && count($this->otherwise->expressions)) { $code .= $idt1 . "default:\n" . $this->otherwise->compile($options, LEVEL_TOP) . "\n"; } return $code . $this->tab . '}'; }
function generate_gives_to($group_list, $fancy_print = true, $attempt = 0) { $recipients = []; $givesto = []; $attempt += 1; foreach ($group_list as $k1 => $group) { $possible_recipients = array_merge(array_slice($group_list, 0, $k1), array_slice($group_list, $k1 + 1)); $possible_recipients = array_diff(flatten($possible_recipients), $recipients); foreach ($group as $k2 => $person) { if (empty($possible_recipients)) { if ($attempt < 10) { return generate_gives_to($group_list, $fancy_print, $attempt); } else { return false; } } $k = array_rand($possible_recipients); $givesto[trim($person)] = trim($possible_recipients[$k]); $recipients[] = $possible_recipients[$k]; unset($possible_recipients[$k]); } } //echo fancy_print($givesto); //return $givesto; return $fancy_print ? fancy_print($givesto) : json_encode($givesto); }
function render() { JS::loadjQuery(); JS::lib('viewslider'); JS::raw('$(function(){$("div.viewslider-view").closest(".formdiv").viewslider();});'); Head::add('viewslider/viewslider', 'css-lib'); return '<div class="formsection viewslider-view"><h3>' . $this->header . '</h3>' . implode('', flatten($this->elements)) . '</div>'; }
/** * @author Sérgio Rafael Siqueira <*****@*****.**> * * @param array $xs * * @return mixed */ function flatten(array $xs) { return array_reduce($xs, function ($carry, $x) { if (is_array($x)) { return array_merge($carry, flatten($x)); } return array_merge($carry, [$x]); }, []); }
function trace() { global $action, $activities, $scheduling; echo '<br>action: ' . $action; echo '<br>activities:'; print_r($activities); echo '<br>scheduling:'; print_r($scheduling); echo '<br>flattened activities: ' . count(flatten($activities)); exit; }
/** * @preserveGlobalState disabled * @runInSeparateProcess */ public function test_show() { Hm_Msgs::add('msg two'); $this->assertTrue(strstr(flatten(join('', Hm_Msgs::show('return'))), 'msgtwo') !== false); ob_start(); Hm_Msgs::show(); $output = ob_get_contents(); ob_end_clean(); $this->assertTrue(strlen($output) > 0); Hm_Msgs::show('log'); }
function trace() { global $action, $activities, $workshop; echo '<br>action: ' . $action; echo '<br>activities:'; print_r($activities); echo '<br>workshop:'; print_r($workshop); echo '<br>flattened activities: ' . count(flatten($activities)); exit; }
static function flatten(array $array) { $flattened = array(); foreach ($array as $k => $v) { if (is_array($v)) { $flattened = array_merge($flattened, flatten($v)); } else { $flattened[] = $v; } } return $flattened; }
function flatten($arg, &$results = array()) { if (is_array($arg)) { foreach ($arg as $a => $p) { if (is_array($p)) { flatten($p, $results); } else { $results[] = $a; } } } return $results; }
function flatten($ary) { $result = array(); foreach ($ary as $x) { if (is_array($x)) { // append flatten($x) onto $result array_splice($result, count($result), 0, flatten($x)); } else { $result[] = $x; } } return $result; }
function flatten($array, $return = array()) { foreach ($array as $k => $v) { if (is_array($v)) { $return = flatten($v, $return); } else { if ($v) { $return[] = $v; } } } return $return; }
function flatten($array) { $l = []; if (is_array($array)) { foreach ($array as $v) { if (is_array($v)) { $l = array_merge($l, flatten($v)); } else { $l[] = $v; } } } return $l; }
public function __call($name, $arguments) { error_log("[FreesideSelfService] {$name} called, sending to " . $this->URL); $request = xmlrpc_encode_request("FS.ClientAPI_XMLRPC.{$name}", flatten($arguments[0])); $context = stream_context_create(array('http' => array('method' => "POST", 'header' => "Content-Type: text/xml", 'content' => $request))); $file = file_get_contents($this->URL, false, $context); $response = xmlrpc_decode($file); if (xmlrpc_is_fault($response)) { trigger_error("[FreesideSelfService] XML-RPC communication error: {$response['faultString']} ({$response['faultCode']})"); } else { //error_log("[FreesideSelfService] $response"); return $response; } }
function flatten($array, $path = "") { $result = array(); foreach ($array as $key => $value) { $fullkey = empty($path) ? $key : $path . "." . $key; if (is_array($value)) { $result = array_merge($result, flatten($value, $fullkey)); } elseif (is_numeric($value)) { $result[$fullkey] = (string) $value; } else { $result[$fullkey] = '"' . $value . '"'; } } return $result; }
/** * Flattens out a multi-dimentional array * * @params array $elements A multi-dimentional array * @params int $depth Index showing the array depth * * @return array $result Returns flattened array */ function flatten($elements, $depth) { $result = array(); foreach ($elements as $key => &$element) { if (isset($depth) == true) { $element['depth'] = $depth; } if (isset($element['children'])) { $children = $element['children']; unset($element['children']); } else { $children = null; } $result[$key] = $element; if (isset($children)) { $result = array_merge($result, flatten($children, $depth + 1)); } } return $result; }
function each_child($func) { if (!$this->children) { return $this; } foreach ($this->children as $i => $attr) { if (isset($this->{$attr}) && $this->{$attr}) { foreach (flatten(array($this->{$attr})) as $i => $child) { if ($func($child) === FALSE) { break 2; } } } } return $this; }
function walk_body($name, $options) { $self = $this; $this->traverse_children(FALSE, function ($child) use($name, $options, &$self) { if ($child instanceof yy_Class) { return FALSE; } if ($child instanceof yy_Block) { foreach ($exps = $child->expressions as $i => $node) { if ($node instanceof yy_Value && $node->is_object(TRUE)) { $exps[$i] = $self->add_properties($node, $name, $options); } } $child->expressions = $exps = flatten($exps); } }); }
/** * Flatten data structure * * Takes a multidimensional array and flattens it down to a single dimensional array. * Will handle sub values of string, numeric, array, and object. * * Example: * * [ * 'foo' => ['foozle' => 'barzle', 'wizzle' => 'wuzzle'], * 'bar' => ['apple' => 'red', 'orange' => ['size' => 'medium', 'shape' => 'round']] * ] * * Will be returned as: * * [ * 'foo.foozle' => 'barzle', * 'foo.wizzle' => 'wuzzle', * 'bar.apple' => 'red', * 'bar.orange.size' => 'medium', * 'bar.orange.shape' => 'round', * ] * * @param array|object $record The record to flatten. * @param string $prepend A key prefix to add to all sub values. * @param string $delimiter The concatenated key delimiter. Defaults to ".". * @return array The flattened $record. */ function flatten($record, $prepend = '', $delimiter = '.') { $results = array(); foreach ($record as $key => $value) { if (is_array($value) or is_object($value)) { $results = array_merge($results, flatten((array) $value, $prepend . $key . $delimiter)); } else { $results[$prepend . $key] = $value; } } return $results; }
<div class="col-md-4"> <h2>Categories</h2> <ul class="nav nav-pills nav-stacked"> <?php while ($row = $categories->fetch()) { ?> <li<?php if ($row['id'] == $category) { echo ' class="active"'; } ?> ><a href="whiteboard/<?php echo $row['id']; ?> /<?php echo flatten($row['name']); ?> "><?php echo $row['name']; ?> </a></li> <?php } ?> <li class="oswebsite"><a href="http://openstreets.co.za"> <img src="img/logo.white.jpg" alt="" /> Open Streets Website</a></li> </ul> </div> </div>
/** * Attaches the invalid messages to the messages * this will set the result to be invalid * @param $propertyItem * @param array $messages validation messages * @return $this|mixed */ public function addInvalidMessage($propertyItem, array $messages) { $this->isValid = false; if (!isset($this->errorMessages[$propertyItem])) { $this->errorMessages[$propertyItem] = []; } $this->errorMessages[$propertyItem][] = array_merge($this->errorMessages[$propertyItem], array_values($messages)); $this->errorMessages = flatten($this->errorMessages); return $this; }
function search($query) { $c = $this->getConnection(); // TODO: Include bind information $users = array(); if ($dn = $this->getConfig()->get('bind_dn')) { $pw = Crypto::decrypt($this->getConfig()->get('bind_pw'), SECRET_SALT, $this->getConfig()->getNamespace()); $r = $c->bind($dn, $pw); unset($pw); if (PEAR::isError($r)) { return $users; } } $schema = static::$schemas[$this->getSchema($c)]; $schema = $schema['user']; $r = $c->search($this->getSearchBase(), str_replace('{q}', $query, $schema['search']), array('attributes' => array_filter(flatten(array($schema['first'], $schema['last'], $schema['full'], $schema['phone'], $schema['mobile'], $schema['email'], $schema['username']))))); // XXX: Log or return some kind of error? if (PEAR::isError($r)) { return $users; } foreach ($r as $e) { // Detect first and last name if only full name is given if (!($first = $e->getValue($schema['first'])) || !($last = $e->getValue($schema['last']))) { $name = new PersonsName($this->_getValue($e, $schema['full'])); $first = $name->getFirst(); $last = $name->getLast(); } $users[] = array('username' => $this->_getValue($e, $schema['username']), 'first' => $first, 'last' => $last, 'email' => $this->_getValue($e, $schema['email']), 'phone' => $this->_getValue($e, $schema['phone']), 'mobile' => $this->_getValue($e, $schema['mobile']), 'backend' => static::$id); } return $users; }
<?php namespace Arrgh; describe('flatten()', function () { it('flattens mult-dimensional arrays', function () { expect(flatten([1, 2, [3, 4], 5, [6, [7, 8]]]))->toWrap(range(1, 8)); }); it('flattens to the specified depth', function () { expect(flatten([1, 2, [3, 4, [5, 6]]], 1))->toWrap([1, 2, 3, 4, [5, 6]]); }); });
function constructor($nodes = array()) { $this->expressions = compact(flatten($nodes)); return $this; }
<?php function flatten_helper($x, $k, $obj) { $obj->flattened[] = $x; } function flatten($ary) { $obj = (object) array('flattened' => array()); array_walk_recursive($ary, 'flatten_helper', $obj); return $obj->flattened; } $lst = array(array(1), 2, array(array(3, 4), 5), array(array(array())), array(array(array(6))), 7, 8, array()); var_dump(flatten($lst));
<?php $un_flatten_array = [[1, 2, [3]], 4]; function flatten($array) { $i = 0; while ($i < count($array)) { while (is_array($array[$i])) { if (!$array[$i]) { array_splice($array, $i, 1); --$i; break; } else { array_splice($array, $i, 1, $array[$i]); } } ++$i; } return $array; } $res = flatten($un_flatten_array); var_dump($res);
function write_sphinx_doc_xml($config, $bib, $process_id) { $dom = new DOMDocument(); $dom->encoding = "utf-8"; $dom->formatOutput = true; foreach ($config as $index) { $file_path = '../sphinx/xml/' . $index['file_path'] . '_' . $process_id . '.xml'; // Each index has its own XML file and fields $doc = $dom->createElement('sphinx:document'); $doc->setAttribute('id', $bib['bnum']); foreach ($index['fields'] as $field) { if (is_array($bib[$field]) or is_object($bib[$field])) { // Concatenate into a single string for indexing $bib[$field] = flatten($bib[$field]); } $tmp = $dom->createElement($field); $tmp->appendChild($dom->createTextNode(trim($bib[$field]))); $doc->appendChild($tmp); unset($tmp); } file_put_contents($file_path, $dom->saveXML($doc) . PHP_EOL, FILE_APPEND | LOCK_EX); unset($file_path); unset($doc); } unset($dom); }
function setAnswer($primkey, $answer) { global $engine; // not an array if ($this->array == false) { // set of enumerated variable if ($this->answertype == ANSWER_TYPE_SETOFENUMERATED || $this->answertype == ANSWER_TYPE_MULTIDROPDOWN) { // specific set of enumerated option $matches = array(); preg_match("/(_[0-9]+_\\b){1}/", $this->completevariablename, $matches); if (sizeof($matches) > 0) { // get indicated option $bracketvalue = str_replace("_", "", $matches[0]); // get current values global $engine; $real = preg_replace("/(_[0-9]+_\\b){1}/", "", $this->completevariablename); $values = explode(SEPARATOR_SETOFENUMERATED, $engine->getAnswer($real)); // set to empty if ($answer == null) { if (inArray($bracketvalue, $values)) { $values[array_search($bracketvalue, $values)] = null; // } $this->variable["answer"] = null; // we don't call storeAnswer for _1_, so set the in-memory value here } else { if (strtoupper($answer) == ANSWER_RESPONSE) { if (inArray($bracketvalue, $values)) { $values[array_search($bracketvalue, $values)] = $bracketvalue; } else { $values[] = $bracketvalue; } $this->variable["answer"] = $bracketvalue; // we don't call storeAnswer for _1_, so set the in-memory value here } } sort($values); // sort ascending //echo "<hr>" . $real . "}}}}"; //print_r($values); return $engine->setAnswer($real, implode(SEPARATOR_SETOFENUMERATED, $values), $this->getDirty()); } else { return $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), $answer); } } else { return $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), $answer); } } else { // not a specific instance (can't have set of enum indicators) if (endsWith($this->completevariablename, "]") == false) { // get current array $currentarray = $engine->getAnswer($this->completevariablename); //echo $this->completevariablename; // answer is not an array, then make it one if (!is_array($answer)) { // we have something! if ($answer != "") { $answer = array($answer); } else { $answer = array(); } } // flatten array (http://stackoverflow.com/questions/9546181/flatten-multidimensional-array-concatenating-keys) $answer = flatten($answer); // store each individual value $bool = true; if (sizeof($answer) > 0) { foreach ($answer as $key => $value) { if (!$engine->setAnswer($this->completevariablename . "[" . $key . "]", $value, $this->getDirty())) { $bool = false; } } } // reset any values no longer present foreach ($currentarray as $ck => $cv) { if (isset($answer[$ck]) == false) { if (!$engine->setAnswer($this->completevariablename . "[" . $ck . "]", null, DATA_DIRTY)) { $bool = false; } } } // store complete array answer if value(s), don't strip any tags! if (sizeof($answer) > 0) { $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), gzcompress(serialize($answer)), false); } else { $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), ""); } return true; } else { // TODO: strip the last [] --> see getBasicName in functions.php for code $varname = trim(substr($this->completevariablename, 0, strrpos($this->completevariablename, "["))); // TODO fix this to always get the correct [ after the last . $index = substr($this->completevariablename, strrpos($this->completevariablename, "[") + 1); $index = trim(substr($index, 0, strlen($index) - 1)); //echo "<br/>" . $this->completevariablename . '---' . $index . '----' . $answer; // get entire answer $ans = $engine->getAnswer($varname); if ($ans == "" || is_null($ans)) { $arr = array(); } else { $arr = $ans; //unserialize(gzuncompress($ans)); } // set of enumerated variable if ($this->answertype == ANSWER_TYPE_SETOFENUMERATED || $this->answertype == ANSWER_TYPE_MULTIDROPDOWN) { // specific set of enumerated option: e.g. Q1_1_[1,2] $matches = array(); preg_match("/(_[0-9]+_\\b){1}/", $varname, $matches); if (sizeof($matches) > 0) { // get indicated option $bracketvalue = str_replace("_", "", $matches[0]); // get current values global $engine; $real = preg_replace("/(_[0-9]+_\\b){1}/", "", $varname); $values = explode(SEPARATOR_SETOFENUMERATED, $engine->getAnswer($real)); // set to empty if ($answer == null) { if (in_array($bracketvalue, $values)) { $values[array_search($bracketvalue, $values)] = null; // } } else { if (strtoupper($answer) == ANSWER_RESPONSE) { if (inArray($bracketvalue, $values)) { $values[array_search($bracketvalue, $values)] = $bracketvalue; } else { $values[] = $bracketvalue; } } } sort($values); // sort ascending $answer = implode(SEPARATOR_SETOFENUMERATED, $values); } else { /* do nothing */ } } else { /* do nothing */ } // update array $arr[$index] = $answer; // flatten array $arr = flatten($arr); // flatten array //print_r($arr); // store updated array first, so the last call sets the in-memory answer properly //$engine->setAnswer($varname, gzcompress(serialize($arr))); // store complete array answer, don't strip any tags! $this->storeAnswer($primkey, $engine->prefixVariableName($varname), gzcompress(serialize($arr)), false); // array answer, then add individual entries if (is_array($answer)) { if (sizeof($answer) > 0) { $temparray[$index] = $answer; $temparray = flatten($temparray); // flatten array //print_r($temparray); foreach ($temparray as $key => $value) { if (!$engine->setAnswer($varname . "[" . $key . "]", $value, $this->getDirty())) { $bool = false; } } } } //print_r($answer); //echo "<hr><hr><hr><br/>"; // store the separate value under the specified name (e.g. Q1[1,1]) // answer itself is an array if (is_array($answer)) { //echo 'STORING: ' . $this->completevariablename; // store array answer, don't strip any tags! $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), gzcompress(serialize($answer)), false); } else { $this->storeAnswer($primkey, $engine->prefixVariableName($this->completevariablename), $answer); } //echo "<hr>in memory value for " . $this->completevariablename . " is: " . $this->variable["answer"]; // return result return true; } } }