I'm trying to make a menu from an array in PHP.
I would like to make it more readable, so I used an array.
My array is the following:
$menu = array(
'calendar' => array(
'text' => 'Calendar',
'rights' => 'user'
),
'customers' => array(
'text' => 'Customers',
'rights' => 'user',
'sub' => array(
'create-new' => array(
'text' => 'Create new customer',
'rights' => 'user'
),
'show-customers' => array(
'text' => 'Show all customers',
'rights' => 'user'
)
)
)
);
And the PHP to parse the array:
buildMenu($menu);
function buildMenu($menu_array, $is_sub=FALSE) {
$attr = (!$is_sub) ? ' id="menu"' : ' class="submenu"';
$menu = "<ul".$attr.">";
foreach($menu_array as $id => $properties) {
foreach($properties as $key => $val) {
if(is_array($val)) {
$sub = buildMenu($val, TRUE);
}
else {
$sub = NULL;
$$key = $val;
}
}
if(!isset($url)) {
$url = $id;
}
$menu .= "<li>".$text."".$sub."</li>";
unset($url, $text, $sub);
}
return $menu . "</ul>";
}
Do I miss something ?
It don't echo me anything.
Thanks for your help.
Just return will not give output you need to either use below code, inside function.
echo $menu . "</ul>";
instead of
return $menu . "</ul>";
or use below code if you return your html output.
echo $output = buildMenu($menu);
instead of
buildMenu($menu);
Related
I am trying to create menu dynamically according to the user input. I have an array like this, I want to get each value by their indices or I want to use the values to create menu by their order:
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
);
Try the following code:
foreach ($menu['main_menu'] as $item => $menu_item) {
if (is_array($menu_item)) {
foreach ($menu_item as $menu_name => $menu_attr) {
echo "menu name: " . $menu_name;
echo '<br/>';
foreach ($menu_attr as $attr => $val) {
echo $attr . "->" . $val;
echo '<br/>';
}
}
}
else{
echo $item.": ".$menu_item;
echo "<br />";
}
}
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
'menu_item4'=>array('php2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
'menu_item5'=>array('development2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item6'=>array('php2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development2' )),
);
$submenus = [];
$mainMenu = [];
$menuStart;
$menuEnd;
//prapring data
foreach($menu['main_menu'] as $item){
if(is_array($item)){
foreach($item as $link){
if(isset($link['sub_menu']) & $link['sub_menu'] != '0'){
$submenus[] = [
'name' => key($item),
'sub_menu' => $link["sub_menu"],
'body' => "<li class='{$link["Class name"]}'><a href='{$link["URL"]}' class='{$link["Class name"]}' id='{$link["menu_id"]}'>" . key($item) . "</a>",
'end' => "</li>"
];
} else {
$mainMenu[] = [
'name' => key($item),
'body' => "<li class='{$link["Class name"]}'><a href='{$link["URL"]}' class='{$link["Class name"]}' id='{$link["menu_id"]}'>" . key($item) . "</a>",
'end' => "</li>"
];
}
}
} else {
$menuStart = "<ul class='{$item}'>";
}
}
/// menu generatig
$menuEnd = '</ul>';
echo $menuStart;
foreach($mainMenu as $menu){
echo $menu['body'];
foreach($submenus as $submenu){
if($submenu["sub_menu"] == $menu['name']){
echo "<ul>";
echo $submenu['body'];
echo "</ul>";
}
}
echo $menu['end'];
}
echo $menuEnd;
Following code may help you.
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
);
foreach($menu['main_menu'] as $menu_name=>$menu_value){
echo "<br><br>menu_name ". $menu_name;
if(is_array ( $menu_value )){
foreach($menu_value as $k=>$v){
if(is_array ( $v )){
foreach($v as $key=>$value)
echo "<br>key=".$key." value=".$value;
}
}
}
}
truy this
foreach($menu['main_menu'] as $menu_name=>$menu_value)
{
if(is_array($menu_value))
{
foreach($menu_value as $value)
{
if(is_array ( $value ))
{
echo "<a href='{$value["URL"]}' class='{$value["Classname"]}'>" . key($menu_value) . "</a><br />"; //
}
}
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP convert nested array to single array while concatenating keys?
Get array's key recursively and create underscore seperated string
Please, read the whole question before answering.
I have this multidimensional array:
$data = array(
'user' => array(
'email' => 'user#example.com',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
I want it flatten, transformed into:
$data = array(
'user.email' => 'user#example.com',
'user.name' => 'Super User',
'user.address.billing' => 'Street 1',
'user.address.delivery' => 'Street 2',
'post' => 'Hello, World!'
);
Important:
The keys are very important to me. I want them concatenated, separated by periods.
It should work with any level of nesting.
Thank you!
Something like this should work:
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
DEMO
Thanks for all the given answers.
I have transformed it in the following, which is an improved version. It eliminates the need of a root prefix, does not need to use references, it is cleaner to read, and it has a better name:
function array_flat($array, $prefix = '')
{
$result = array();
foreach ($array as $key => $value)
{
$new_key = $prefix . (empty($prefix) ? '' : '.') . $key;
if (is_array($value))
{
$result = array_merge($result, array_flat($value, $new_key));
}
else
{
$result[$new_key] = $value;
}
}
return $result;
}
Try this
<?php
$data = array(
'user' => array(
'email' => 'user#example.com',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
function prefixKey($prefix, $array)
{
$result = array();
foreach ($array as $key => $value)
{
if (is_array($value))
$result = array_merge($result, prefixKey($prefix . $key . '.', $value));
else
$result[$prefix . $key] = $value;
}
return $result;
}
var_dump(prefixKey('', $data));
?>
Outputs
array
'user.email' => string 'user#example.com' (length=16)
'user.name' => string 'Super User' (length=10)
'user.address.billing' => string 'Street 1' (length=8)
'user.address.delivery' => string 'Street 2' (length=8)
'post' => string 'Hello, World!' (length=13)
test this out here
i passed by reference so no need for returns. just hand over the array storage.
$store = array();
function flatten($array,&$storage,$parentKey = ''){
foreach($array as $key => $value){
$itemKey = (($parentKey)? $parentKey.'.':'').$key;
if(is_array($value)){
flatten($value,$storage,$itemKey);
} else {
$storage[$itemKey] = $value;
}
}
}
flatten($data,$store);
var_dump($store);
Use recursion such as this:
function process_data( $data, $parent_key ){
if ( ! is_array( $data ) ){
return $data;
}
$flattened_array = array();
foreach( $data as $key => $item ){
$flattened_key = $parent_key . '.' . $key;
$flattened_array[ $flattened_key ] = process_data( $item, $flattened_key );
}
return $flattened_array;
}
how can i print the whole multidimensional array by using foreach?
<?php
$shop=array // main array
(
"laptop"=>array
(
"conpaq",
"IBM",
"DELL",
"Lenovo"
),
"printer"=>array
(
"canon",
"Hp"
),
"Tabs"=>array
(
"Hp",
"Dell",
"deny"
)
);
This one is a simple list using recursion, it also have tabs to make it more clear when there's a new array-group.
Please try it and adjust for your code.
$shop = array(
'computers' => array(
'dell' => array(
'i7' => array(
'model1' => 'Model 1',
'model2' => 'Model 2',
),
'i5' => 'Model 1'
),
'hp' => array(
'model1' => 'Model 1'
)
),
'printers' => array(
'Epson' => 'Model 1'
)
);
function printProducts($products, $tabsCount = 0){
$result = ''; $tabs = '';
for($i = 0; $i < $tabsCount; $i++){ $tabs .= ' '; }
foreach($products AS $index=>$product){
if(is_array($product)){
$result .= $tabs.$index.'<br>';
$result .= printProducts($product, $tabsCount+1);
}else{
$result .= $tabs.$product.'<br>';
}
}
return $result;
}
echo printProducts($shop);
Ask if there is something you don't understand.
for 2 levels and without recursion. Recusion would be better but this will work.
foreach($shop as $value) {
if (is_array($value)) {
foreach($shop as $value) {
echo "$value<br />";
}
} else {
echo "$value<br />";
}
}
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP convert nested array to single array while concatenating keys?
Get array's key recursively and create underscore seperated string
Please, read the whole question before answering.
I have this multidimensional array:
$data = array(
'user' => array(
'email' => 'user#example.com',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
I want it flatten, transformed into:
$data = array(
'user.email' => 'user#example.com',
'user.name' => 'Super User',
'user.address.billing' => 'Street 1',
'user.address.delivery' => 'Street 2',
'post' => 'Hello, World!'
);
Important:
The keys are very important to me. I want them concatenated, separated by periods.
It should work with any level of nesting.
Thank you!
Something like this should work:
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
DEMO
Thanks for all the given answers.
I have transformed it in the following, which is an improved version. It eliminates the need of a root prefix, does not need to use references, it is cleaner to read, and it has a better name:
function array_flat($array, $prefix = '')
{
$result = array();
foreach ($array as $key => $value)
{
$new_key = $prefix . (empty($prefix) ? '' : '.') . $key;
if (is_array($value))
{
$result = array_merge($result, array_flat($value, $new_key));
}
else
{
$result[$new_key] = $value;
}
}
return $result;
}
Try this
<?php
$data = array(
'user' => array(
'email' => 'user#example.com',
'name' => 'Super User',
'address' => array(
'billing' => 'Street 1',
'delivery' => 'Street 2'
)
),
'post' => 'Hello, World!'
);
function prefixKey($prefix, $array)
{
$result = array();
foreach ($array as $key => $value)
{
if (is_array($value))
$result = array_merge($result, prefixKey($prefix . $key . '.', $value));
else
$result[$prefix . $key] = $value;
}
return $result;
}
var_dump(prefixKey('', $data));
?>
Outputs
array
'user.email' => string 'user#example.com' (length=16)
'user.name' => string 'Super User' (length=10)
'user.address.billing' => string 'Street 1' (length=8)
'user.address.delivery' => string 'Street 2' (length=8)
'post' => string 'Hello, World!' (length=13)
test this out here
i passed by reference so no need for returns. just hand over the array storage.
$store = array();
function flatten($array,&$storage,$parentKey = ''){
foreach($array as $key => $value){
$itemKey = (($parentKey)? $parentKey.'.':'').$key;
if(is_array($value)){
flatten($value,$storage,$itemKey);
} else {
$storage[$itemKey] = $value;
}
}
}
flatten($data,$store);
var_dump($store);
Use recursion such as this:
function process_data( $data, $parent_key ){
if ( ! is_array( $data ) ){
return $data;
}
$flattened_array = array();
foreach( $data as $key => $item ){
$flattened_key = $parent_key . '.' . $key;
$flattened_array[ $flattened_key ] = process_data( $item, $flattened_key );
}
return $flattened_array;
}
Ok, so say I have an array as follows:
$buttons = array(
'mlist' => array(
'title' => 'Members',
'href' => $scripturl . '?action=mlist',
'show' => $context['allow_memberlist'],
'sub_buttons' => array(
'mlist_view' => array(
'title' => 'View the Member List',
'href' => $scripturl . '?action=mlist',
'show' => true,
),
'mlist_search' => array(
'title' => 'Search for Members',
'href' => $scripturl . '?action=mlist;sa=search',
'show' => true,
'is_last' => true,
),
),
),
'home' => array(
'title' => 'Home',
'href' => $scripturl,
'show' => true,
'sub_buttons' => array(
),
'is_last' => $context['right_to_left'],
),
'help' => array(
'title' => 'Help',
'href' => $scripturl . '?action=help',
'show' => true,
'sub_buttons' => array(
),
),
);
I need to sort through this array and return all indexes of it in another array as an index, and the values of these arrays will be the title. So it should return an array as follows:
array(
'mlist' => 'Members',
'mlist_view' => 'View the Member List',
'mlist_search' => 'Search for Members',
'home' => 'Home',
'help' => 'Help',
);
How can this be achieved easily? Basically, need the key of each array if a title is specified and need to populate both within another array.
The following snippet loops over all of the arrays (recursively) to extract the key/title pairs.
$index = array();
$iterator = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($buttons)), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
if (array_key_exists('title', $value)) {
$index[$key] = $value['title'];
}
}
var_dump($index);
How can this be achieved easily?
initialize an empty, new array
foreach the $buttons array with key and value
extract title from value
set the key in the new array with the title
done.
Edit: In case a recursive array iterator catches too much (identifying elements as children while they are not - just being some other array), and you don't want to write an extension of the recursive iterator class, stepping through all children can be solved with some "hand written" iterator like this:
$index = array();
$childKey = 'sub_buttons';
$iterator = $buttons;
while(list($key, $item) = each($iterator))
{
array_shift($iterator);
$index[$key] = $item['title'];
$children = isset($item[$childKey]) ? $item[$childKey] : false;
if ($children) $iterator = $children + $iterator;
}
This iterator is aware of the child key, so it will only iterate over childs if there are some concrete. You can control the order (children first, children last) by changing the order:
if ($children) $iterator = $children + $iterator;
- or -
if ($children) $iterator += $children;
I'm sure my answer is not most efficient, but using many foreach loops and if checks, it can be done. However, with my solution if you nested another array inside of say 'mlist_view' that you needed to get a title from, it would not work. My solution works for a max of 2 arrays inside of arrays within buttons. A better (and more general purpose solution) would probably involve recursion.
$result = array();
foreach($buttons as $field => $value) {
foreach($value as $nF => $nV) {
if($nF === 'title') {
$result[$field] = $nV;
}
if(is_array($nV)) {
foreach($nV as $name => $comp) {
if(is_array($comp)) {
foreach($comp as $nnF => $nnV) {
if($nnF === 'title') {
$result[$name] = $nnV;
}
}
}
}
}
}
}
foreach($result as $f => $v) {
echo $f.": ".$v."<br/>";
}
This works for your value of $buttons, fairly simple:
function get_all_keys($arr) {
if (!is_array($arr)) return array();
$return = array();
foreach (array_keys($arr) as $key) {
if (is_array($arr[$key])
&& array_key_exists('title', $arr[$key]))
$return[$key] = $arr[$key]['title'];
$return = array_merge($return, get_all_keys($arr[$key]));
}
return $return;
}
echo "<pre>";
print_r(get_all_keys($buttons));
echo "</pre>";
Which returns:
Array
(
[mlist] => Members
[mlist_view] => View the Member List
[mlist_search] => Search for Members
[home] => Home
[help] => Help
)