Basically, I need to serialize multiple checkboxes before saving them in database and unserialize before displaying the form.
<input type="checkbox" name="list[option1]" value="1">
<input type="checkbox" name="list[option2]" value="1">
<input type="checkbox" name="list[option3]" value="1">
Could someone point me to the right direction please?
I've tried the following code to generate the checkboxes, but it's not working after the request.
Selected options are not getting populated to the form (other fields are fine)
<?php
$form->bind($_POST, $entity);
....
foreach ($list as $key => $option) {
$form->add(new Check("list[$key]", array('value' => 1)));
}
I suppose the same issue exists with using multi-choice select boxes.
I think you've got a typo. Try:
<?php
$form->bind($_POST, $entity);
....
foreach ($list as $key => $option) {
$form->add(new Check($list[$key], array('value' => 1)));
}
On a side note, the Phalcon\Tag helper can be used to generate HTML.
<?php
echo Phalcon\Tag::checkField(array($list[$key], "value" => "1"));
You can using my code Fdola.com.
Use
<?php
$list_module = new \App\Vendor\Fdola\Forms\CheckBoxList('list_module', ['a' => 'A', 'b' => 'B'], ['a'], ['class' => 'checkBoxList']);
$list_module->setLabel('Module hiển thị banner:');
$list_module->addValidators([
new \Phalcon\Validation\Validator\PresenceOf([
'message' => '<b>:field</b> không được phép rỗng'
])
]);
$this->add($list_module);
<?php
/**
* Created by PhpStorm.
* User: thanhansoft
* Date: 4/29/2016
* Time: 4:21 PM
*/
namespace App\Vendor\Fdola\Forms;
use Phalcon\Http\Request;
use Phalcon\Tag;
class CheckBoxList extends \Phalcon\Forms\Element {
private $_data;
private $_dataOld;
public function __construct($name, $data, $dataOld = null, $attribute = null) {
$this->_data = $data;
$this->_dataOld = $dataOld;
parent::__construct($name, $attribute);
}
public function render($attribute = null) {
$get_value = $this->getValue();
if ($get_value) {
$data = $get_value;
} else {
$data = $this->_dataOld;
}
$tag = new Tag();
$string = '';
if ($this->_data) {
foreach ($this->_data as $key => $value) {
$arr = ['id' => $this->_name . '-' . $key, 'name' => $this->_name . '[]', 'value' => $key];
if ($data && in_array($key, $data)) {
$arr['checked'] = 'checked';
}
$string .= '<label>' . $tag::checkField($arr) . ' ' . $value . '</label>';
}
}
if (isset($this->_attributes['class'])) return '<div class="' . $this->_attributes['class'] . '">' . $string . '</div>';
return $string;
}
}
Related
I need to convert a PHP array into HTML tag attributes, with spaces and quotes, this is an example:
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
This is the result I need to achieve:
attr1="value1" id="example" name="john" class="normal"
There is any PHP function to do it?
I am trying these:
http_build_query
array_walk
You can also use this easy one line code, please follwo below code::
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
$data = str_replace("=", '="', http_build_query($array, null, '" ', PHP_QUERY_RFC3986)).'"';
echo $data;
Output
attr1="value1" id="example" name="john" class="normal"
I use the following function:
function buildAttributes($attributes)
{
if (empty($attributes))
return '';
if (!is_array($attributes))
return $attributes;
$attributePairs = [];
foreach ($attributes as $key => $val)
{
if (is_int($key))
$attributePairs[] = $val;
else
{
$val = htmlspecialchars($val, ENT_QUOTES);
$attributePairs[] = "{$key}=\"{$val}\"";
}
}
return join(' ', $attributePairs);
}
It correctly escapes special html characters and supports boolean attributes (attributes without value). The following input:
[
'name' => 'firstname',
'value' => 'My Name',
'required'
]
Will produce:
name="firstname" value="My Name" required
Use a foreach loop to get the value and key.
$array = array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal');
foreach ($array as $key => $value) {
echo $key . '="' . htmlspecialchars($value) . '" ';
}
If you wanted to use a function, you could just make your own such as the following.
$array = array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal');
echo buildTag($array);
function buildTag ($array) {
$tag = '';
foreach ($array as $key => $value) {
$tag .= $key . '="' . htmlspecialchars($value) . '" ';
}
return $tag;
}
You could also utilize array_map() in conjunction with array_keys() to build your $key=$value string.
Wrapped in array_filter() to remove empty items and ultimately use implode() to glue your items together.
$array = array(
'attr1' => 'value1',
'id' => 'example',
'name' => 'john',
'class' => 'normal',
'c' => null,
'd' => '',
'e' => '"abc"'
);
$attributes = implode( ' ', array_filter( array_map( function ( $key, $value ) {
return $value ? $key . '="' . htmlspecialchars( $value ) . '"' : false;
}, array_keys( $array ), $array ) ) );
echo "<div " . $attributes . "></div>";
Result:
<div attr1="value1" id="example" name="john" class="normal" e=""abc""></div>
The shortest one-line function to do that would be:
function add_attributes($attributes){
return urldecode(http_build_query(array_map(function($v){ return '"'.((string) $v).'"'; }, $attributes), '', ' '));
}
You can use it like this:
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
echo '<div '.add_attributes($array).'></div>';
will produce:
<div attr1="value1" id="example" name="john" class="normal"></div>
You can use this function:
public static function arrayToStringTags( $array )
{
$tags = '';
if(!(is_array($array) && !empty($array)))
{
return $tags;
}
foreach($array as $key => $value)
{
$tags .= $key. '="'. $value. '" ';
}
return $tags;
}
I am trying to use an array to output a form with the following function:
public function createArrayForm($table, $do, $formDesc = '', $id, $array, $markFields = false) {
if (!isset($table) && !isset($do)) {
self::show_error('One or more parameters are missing in ' . __FUNCTION__);
} elseif ($table == 'update' && !isset($id)) {
self::show_error('For this form to be built, and ID must be set. Missing parameter `ID` in ' . __FUNCTION__);
}
if (is_array($array) && $do == 'insert') {
$out .= '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>';
$out .= '<div class="form-desc">' . $formDesc . '</div>';
$out .= $markFields ? '<h3>Input Fields</h3>' : '';
foreach ($array as $type => $fieldname) {
if ($type == 'input') {
$out .= generateInputField($fieldname);
}
}
$out .= $markFields ? '<h3>Content Fields</h3>' : '';
foreach ($array as $type => $fieldname) {
if ($type == 'textarea') {
$out .= generateTextarea($fieldname, $cke);
}
}
$out .= $markFields ? '<h3>Images Fields</h3>' : '';
foreach ($array as $type => $fieldname) {
if ($type == 'image') {
$out .= generateImgField($fieldname);
}
}
$out .= form_hidden('user_data', '1');
$out .= form_hidden('id', self::generateID());
$out .= form_close();
return $out;
}
And call:
$arr = array("textarea"=>"project_name", "input"=>"created", "input"=>"last_modified", "input"=>"published");
echo $automate->createArrayForm('projects', 'insert', 'Some form desc', '123', $arr, true);
But it only outputs:
When it should look something like this:
Only one of each, for example input, is returned. Rather than all instances of it. So "input"=>"created", "input"=>"last_modified", "input"=>"published" should make three inputs, but it only returns one.
You're re-using array keys. So
$arr = array("textarea"=>"project_name", "input"=>"created", "input"=>"last_modified", "input"=>"published");
will end up looking like this:
$arr = array("textarea"=>"project_name", "input"=>"published");
Instead, modify your code to something like this:
$arr = array("textarea"=>array("project_name"), "input"=>array("created", "last_modified", "published"));
Then take those individual arrays, and iterate through them.
foreach ($array['input'] as $fieldname) { // etc and so on
In PHP, you cannot have arrays that share keys.
You'll be best creating a simple array, and creating sub-entries, so that you maintain order, but can have more than one input/textarea.
Like so:
$arr = array(
array('type' => 'textarea', 'name' => 'project_name'),
array('type' => 'input', 'name' => 'created'),
array('type' => 'input', 'name' => 'published'),
array('type' => 'input', 'name' => 'last_modified')
)
This would also allow you to add more parameters than type/name.
The problem is that you use the same key for everything in the array.
A possibility would be to exchange values and keys
$arr = array("textarea"=>"project_name", "input"=>"created", "input"=>"last_modified", "input"=>"published");
[...]
foreach ($array as $fieldname => $type) {
if ($type == 'textarea') {
$out .= generateTextarea($fieldname, $cke);
}
}
[...]
how to print dynamical add properties in bellow class?
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
set class object like bellow
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
$car2 = new Car();
$car2->setInfo(array('anme1' => 'value1', 'anme2' => 'value2'));
now I want to to print car object bellow
make = Toyota
model = scp10
Try :
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo $car1->make;
echo $car1->model;
<?php
class Car {
function __construct() {
}
function setInfo($car_arr) {
foreach ($car_arr as $key => $value) {
$this->{$key} = $value;
}
}
}
$car1 = new Car();
$car1->setInfo(array('make' => 'Toyota', 'model' => 'scp10'));
echo "Make value is : " . $car1->make. ", Model value is : ". $car1->model;
?>
above code output Make value is : Toyota, Model value is : scp10
Please consider storing the properties explicitly like I pointed out in this answer:
<?php
class Car {
private $data = array();
function setInfo(array $carInfo) {
foreach ($carInfo as $k => $v) {
$this->data[$k] = $v;
}
return $this;
}
function __set($key, $val) {
$this->data[$key] = $val;
}
function __get($key) {
return $this->data[$key];
}
}
$car = new Car();
$car->setInfo(array('make' => 'Toyota', 'warranty' => '5 years'));
I'd consider it more "clean", but that's probably debatable.
I think you look for something like this PHP Magic Methods
For example this one:
<?php
class A
{
public $var1;
public $var2;
public static function __set_state($an_array) // As of PHP 5.1.0
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}
$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';
eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>
This will be helpful too.
You can fetch all properties using get_object_vars():
$vars = get_object_vars($car1);
foreach ($vars as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
I want know how to add custom attribute for option in a select field of Zend form.
PHP:
$option_values = array("multiOptions" => array(
"US" => "United States",
"CA" => "Canada",
));
$type=array('big','small');
$option= new Zend_Form_Element_Select('option', $option_values);
HTML:
<select>
<option value='US' type='big'>United States</option>
<option value='CA' type='small'>Canada</option>
</select>
How to add this type attribute in the option?
It is not possible using ZF's implementation of Zend_Form_Element_Select. You need to create your own element. I have done something similar, here's the relevant code:
<?php
require_once 'Zend/Form/Element/Select.php';
/**
* Select, but with the possibility to add attributes to <option>s
* #author Dominik Marczuk
*/
class Zend_Form_Element_SelectAttribs extends Zend_Form_Element {
public $options = array();
public $helper = 'selectAttribs';
/**
* Adds a new <option>
* #param string $value value (key) used internally
* #param string $label label that is shown to the user
* #param array $attribs additional attributes
*/
public function addOption ($value,$label = '',$attribs = array()) {
$value = (string) $value;
if (!empty($label)) $label = (string) $label;
else $label = $value;
$this->options[$value] = array(
'value' => $value,
'label' => $label
) + $attribs;
return $this;
}
}
Put this into /library/Zend/Form/Element/SelectAttribs.php. You also need a helper to render the element. Put it into your view helpers directory, name it SelectAttribs.php as well. Here's the contents of my file:
<?php
require_once 'Zend/View/Helper/FormElement.php';
class Zend_View_Helper_SelectAttribs extends Zend_View_Helper_FormElement {
public function selectAttribs($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n") {
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
. ' name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. ">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ($options as $opt_value => $option) {
$opt_disable = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
$list[] = $this->_build($option, $disabled);
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list) . "\n</select>";
return $xhtml;
}
protected function _build($option, $disabled) {
$html = '<option';
foreach ($option as $attrib => $value) {
$html .= " $attrib=\"$value\"";
}
return $html.$disabled.">".$option['label']."</option>";
}
}
With this, you should be ready to go:
$elt = new Zend_Form_Element_SelectAttribs('whatever');
$elt->addOption($value,$label,array('attribname' => 'attribvalue'));
Using addMultiOption($value,$label) I just set the value parameter to something like:
$value = $id . '" ref="' . $ref;
and when it renders you get:
<option value="<idValue>" ref="<refValue"><labelValue></option>
Hope this helps....
Okay, value gets escaped but optionClasses does not so inside the loop that adds the addMultiOptions(val,lable) I do something like this:
$optionClasses[<val>] = 'ref_' . <val> . '" ref="' . <ref>;
and then after the loop just do a setAttrib('optionClasses',$optionClasses)
And that actually works...
I answered this for another question but could not find a way to add a comment here to reference it; It was Zend Framework addMultiOption adding custom parameters like "rel" for options
I didn't find #mingos's answer complete and had some issues with implementing setting the value. His answer helped a lot with what needed to be extended and changed however. Once I had that start the rest was pretty easy. I just extended ZF1's Select and overrode where I needed:
/**
* Select, now with abbility to specify attributes on <Option>, addMultiOption has new syntax
* #author Seth Miller
*/
class MyNamespace_Form_Element_SelectAttribs extends Zend_Form_Element_Select {
public $options = array();
public $helper = 'selectAttribs';
/**
* Add an option
*
* #param string $option
* #param string $value
* #return Zend_Form_Element_Multi
*/
public function addMultiOption($value, $label = '', $attribs = array()) {
$value = (string) $value;
if (!empty($label)) {
$label = (string) $label;
}
else {
$label = $value;
}
$this->_getMultiOptions();
if (!$this->_translateOption($value, $label)) {
$this->options[$value] = array(
'value' => $value,
'label' => $label
) + $attribs;
}
return $this;
}
/**
* Add many options at once
*
* #param array $options
* #return Zend_Form_Element_Multi
*/
public function addMultiOptions(array $options) {
foreach ($options as $optionKey => $optionProperties) {
if (is_array($optionProperties)
&& array_key_exists('key', $optionProperties)
&& array_key_exists('value', $optionProperties)
) {
if(array_key_exists('key', $optionProperties)) $optionKey = $optionProperties['key'];
$this->addMultiOption($optionKey, $optionProperties['value'], $optionProperties['attribs']);
}
else {
$this->addMultiOption($optionKey, $optionProperties);
}
}
return $this;
}
public function isValid($value, $context = null)
{
if ($this->registerInArrayValidator()) {
if (!$this->getValidator('InArray')) {
$multiOptions = $this->getMultiOptions();
$options = array();
foreach ($multiOptions as $optionKey => $optionData) {
// optgroup instead of option label
if (is_array($optionData['options'])) {
$options = array_merge($options, array_keys($optionData['options']));
}
else {
$options[] = $optionKey;
}
}
$this->addValidator(
'InArray',
true,
array($options)
);
}
}
return parent::isValid($value, $context);
}
}
And the view helper:
class MyNamespace_View_Helper_SelectAttribs extends Zend_View_Helper_FormElement {
public function selectAttribs($name, $value = null, $attribs = null, $options = null, $listsep = "<br />\n") {
$info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
extract($info); // name, id, value, attribs, options, listsep, disable
// force $value to array so we can compare multiple values to multiple
// options; also ensure it's a string for comparison purposes.
$value = array_map('strval', (array) $value);
// check if element may have multiple values
$multiple = '';
if (substr($name, -2) == '[]') {
// multiple implied by the name
$multiple = ' multiple="multiple"';
}
if (isset($attribs['multiple'])) {
// Attribute set
if ($attribs['multiple']) {
// True attribute; set multiple attribute
$multiple = ' multiple="multiple"';
// Make sure name indicates multiple values are allowed
if (!empty($multiple) && (substr($name, -2) != '[]')) {
$name .= '[]';
}
}
else {
// False attribute; ensure attribute not set
$multiple = '';
}
unset($attribs['multiple']);
}
// now start building the XHTML.
$disabled = '';
if (true === $disable) {
$disabled = ' disabled="disabled"';
}
// Build the surrounding select element first.
$xhtml = '<select'
.' name="'.$this->view->escape($name).'"'
.' id="'.$this->view->escape($id).'"'
.$multiple
.$disabled
.$this->_htmlAttribs($attribs)
.">\n ";
// build the list of options
$list = array();
$translator = $this->getTranslator();
foreach ((array) $options as $optionKey => $optionData) {
if (isset($optionData['options'])) {
$optDisable = '';
if (is_array($disable) && in_array($optionData['value'], $disable)) {
$optDisable = ' disabled="disabled"';
}
if (null !== $translator) {
$optValue = $translator->translate($optionData['value']);
}
$optId = ' id="'.$this->view->escape($id).'-optgroup-'
.$this->view->escape($optionData['value']).'"';
$list[] = '<optgroup'
.$optDisable
.$optId
.' label="'.$this->view->escape($optionData['value']).'">';
foreach ($optionData['options'] as $optionKey2 => $optionData2) {
$list[] = $this->_build($optionKey2, $optionData2, $value, $disable);
}
$list[] = '</optgroup>';
}
else {
$list[] = $this->_build($optionKey, $optionData, $value, $disable);
}
}
// add the options to the xhtml and close the select
$xhtml .= implode("\n ", $list)."\n</select>";
return $xhtml;
}
/**
* Builds the actual <option> tag
*
* #param string $value Options Value
* #param string $label Options Label
* #param array $selected The option value(s) to mark as 'selected'
* #param array|bool $disable Whether the select is disabled, or individual options are
* #return string Option Tag XHTML
*/
protected function _build($optionKey, $optionData, $selected, $disable)
{
if (is_bool($disable)) {
$disable = array();
}
$opt = '<option';
foreach ($optionData as $attrib => $attribValue) {
$opt .= ' '.$this->view->escape($attrib).'="'.$this->view->escape($attribValue).'"';
}
// selected?
if (in_array((string) $optionData['value'], $selected)) {
$opt .= ' selected="selected"';
}
// disabled?
if (in_array($optionData['value'], $disable)) {
$opt .= ' disabled="disabled"';
}
$opt .= '>' . $this->view->escape($optionData['label']) . "</option>";
return $opt;
}
}
And implementation in a form would be something like:
$selectElement = new MyNamespace_Form_Element_SelectAttribs('selectElementName');
$selectElement->addMultiOption($value, $label, array('data-custom' => 'custom data embedded in option tag.');
I hope that helps someone. Thanks.
mingos,
you forgot about setvalue method of multiselect.
you shoul add something like:
...
foreach ($options as $opt_value => $option) {
$opt_disable = '';
$opt_selected = '';
if (is_array($disable) && in_array($opt_value, $disable)) {
$opt_disable = ' disabled="disabled"';
}
if (in_array($opt_value,$value)) {
$opt_selected = ' selected="selected"';
}
$list[] = $this->_build($option, $disabled, $opt_selected);
}
...
and
protected function _build($option, $disabled, $opt_selected) {
$html = '<option';
foreach ($option as $attrib => $value) {
$html .= " $attrib=\"$value\"";
}
return $html . $disabled . $opt_selected . " foo>" . $option['label'] . "</option>";
}
You could extend / overwrite the Zend_View_Helper_FormSelect helper but the real problem is going to be getting the extra data into each option.
By default, Zend_Form_Element_Select (via Zend_Form_Element_Multi) expects two strings for each option, one for the value attribute and an optional one for the text content. You may need to create your own element to handle the extra data.
No need for custom form element at all, what u can do is:
$element->setAttrib('disable', array(1, 2, 5));
As explained at http://pietervogelaar.nl/set-attribute-on-select-option-with-zend_form/
use Zend\Form\Element;
use Zend\Form\Form;
$select = new Element\Select('language');
$select->setLabel('Which is your mother tongue?');
$select->setValueOptions([
[
'value' => '0',
'label' => 'French',
'attributes' => [
'data-locale' => 'fr'
],
],
[
'value' => '1',
'label' => 'Italian',
'disabled' => true,
],
]);
$form = new Form('language');
$form->add($select);
I found this way much easier than any of the above suggestions
I'm not so strong with arrays but I need to determine how to count the number of parents a child array has in order to determine the indenting to display it as an option in a SELECT.
So, if I have this array:
array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
How would I go about determining how many parents 'City' has in order to translate that into the number of spaces I want to use as an indent?
Thanks for any help.
EDIT: Let's see if I can explain myself better:
I have this code I'm using to build the OPTIONS list for a SELECT:
function toOptions($array) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children']);
}
}
return $html;
}
print toOptions($list);
So, I'm trying to determine how to get the number of parents in order to add spaces before the title in this line:
$html .= $value['title'];
Like:
$html .= " " . $value['title'];
But, I'm not sure how to figure out how many spaces to add.
Hopefully this is more clear.
Thanks for any help so far.
$x = array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
// This function do something with the key you've found in the array
function visit($name, $depth)
{
echo $name . ' has ' . $depth . ' parents.';
}
// This function visits all the contents aff $array
function find_recursive($array, $depth = 0)
{
if (is_array($array)) {
foreach ($array as $k => $value) {
visit($k, $depth + 1);
find_recursive($array, $depth + 1);
}
}
}
For visiting:
find_recursive($x);
Well. Off the top what you are dealing with is a multi dimensional array.
You could run a count w/ foreach on each level of the array, and use the count number returned +1 for each level the foreach loops through.
I'm not sure if this answers your question, but I am trying to see exactly what it is you are trying to achieve.
As you are already using a recursive function to display that data, you can just extend your function. There is no need to traverse the array more often than one time:
function getWhitespaces($count) {
$result = '';
while($count--) {
$result .= '$nbsp;';
}
return $result;
}
function toOptions($array, $level=0) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= getWhitespaces($level) + $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children'], $level + 1);
}
}
return $html;
}
print toOptions($list);
Try the following.. Your solution screams for recursion in my mind. Its a bit ugly but it seems to work
$totraverse = array(
'Moon' => array(
'Dark Side' => "Death Valley"
),
'Halley Commet' => "Solar System",
'World' => array(
'North America' => array(
'Canada' => array(
'City' => 'Toronto'
)
), 'South America' => array(
'Argentina' => array(
'City' => 'Toronto'
)
)
)
);
function traverse($totraverse_, $path="", $count=0) {
global $array;
// echo count($totraverse_) . " count\n";
if (!is_array($totraverse_)) {
echo "returning $path and $key\n";
return array($path, $count);
} else {
foreach ($totraverse_ as $key => $val) {
echo "assting $path and $key\n";
$result = traverse($val, $path . "/" . $key, $count + 1);
if($result){
$array[]=$result;
}
}
}
echo false;
}
$array = array();
traverse($totraverse);
foreach($array as $item){
echo "{$item[0]}--->{$item[1]}\n";
}