multidimensional array - php

i have a multidimensional array like this
$role = array (
'Dashboard' => null,
'Students' =>
array (
'Admission' => array ( 0 => 'Entry' ,1 => 'Review' , 2 => 'Approved/Reject'
),
'Search' => null,
'AdvanceSearch' => null,
'Courses' => null
),
'HR' => array ('Settings' => null),
'Employee Management' => array ( 0 => 'Entry',1 => 'Association',2 => 'Search' ),
'Employee Attendance' => null,
'Payroll' => array (0 => 'Generate Pay Slip',1 => 'Payroll Run' , 2 => 'Payroll Revert',3 => 'View Pay Slips'),
'Finance' => null,
'More' => null);
and i want to print this array result in my html as
i am trying to do this by using recursion but unable to do that as DIV are not properly closed ..
here is the code that i am trying in my html
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div></div>";
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div></div>";
}
}
//
}
}
RecursiveWrite($role, $child);
?>
here is working code
How can i get this Any suggestion ... ?

Your Problem is missing closing div after recursion
Try this Function
function RecursiveWrite($array, $child )
{
$parent_array_size = count($array);
foreach ($array as $key => $vals)
{
if(is_array($vals))
{
$inner_array_size = count($vals);
echo "<div class='deep'><div class='extra'><input type='checkbox'/> ".$key."</div>";
RecursiveWrite($vals,$child);
echo "</div>";
}
else
{
if(is_numeric($key)){
echo "<span class='single'><input type='checkbox' class=''/> ".$vals."</span>";
}else{
echo "<div class='single'><input type='checkbox'/> ".$key." </div>";
}
}
}
}
Use This Css
<style type="text/css">
.parent {border: solid 1px #000;}
.parent div {border: solid 1px #000; margin:5px;}
.extra {border:0px !important;}
.single {margin-left:10px !important; border:0px !important;}
span.single {display:inline-block; margin-left:20px;}
</style>
Use this to call your Function
<div class="parent"><? RecursiveWrite($role, $child);?></div>
Put all the code Provided in one page with your array.
For better Codding standard you should Septate your style html and php for this try your luck ;)

You're not closing the div in the right places, when calling the recursion, right after ending the recursion you need to write the ending div:
open div
run recursion
close div
As well, you have two unnecessary div closing. Always make sure you open as many div as you close and vice versa. I've marked the places that needed to be changed in the code.
code:
<?php
$child = 0;
function RecursiveWrite($array, $child ) {
$parent_array_size = count($array);
foreach ($array as $key => $vals) {
if(is_array($vals)){
$inner_array_size = count($vals);
echo "<div class='main clear'><input type='checkbox'/> ".$key." ";
RecursiveWrite($vals,$child);
echo "</div>"; /* <== ADD THIS */
}else{
$child = 0;
if(is_numeric($key)){
echo " <div class='left'> <input type='checkbox' class=''/> ".$vals." </div>"; /* <== REMOVE EXTRA DIV */
}else{
echo "<div class='clear'><input type='checkbox'/> ".$key." </div>"; /* <== REMOVE EXTRA DIV */
}
}
//
}
}
RecursiveWrite($role, $child);
?>
you can find a working example at http://codepad.viper-7.com/507rLc

Related

Unexpected asynchronous like behavior

I came across an unexpected behavior while creating drop downs.
DropDown.php
function getValue($content, $options){
if($options["valueByName"])
return $content;
else
return $content["value"];
}
function getName($content, $options){
if($options["valueByName"])
return $content;
else
return $content["name"];
}
function isSelected($content, $options){
if(isset($options["selected"])){
if(getValue($content, $options) == $options["selected"])
return " selected ";
else
return "";
}
else
if(getValue($content, $options)=="")
return " selected ";
else
return "";
}
function renderOption($content, $options){
echo (
"<option value=\"".getValue($content, $options)."\""
.isSelected($content, $options).">"
.getName($content, $options).
"</option>");
}
$asdf123 = 0; #<-------------------------------------IMPORTANT
function DropDownMenu($contents, $options)
{
$id = $options["id"];
$name = $options["name"];
$style = $options["style"];
$flag = $options["flag"];
$firstIsDefault = $options["firstIsDefault"];
global $asdf123; #<-------------------------------------IMPORTANT
echo($asdf123++);
echo ("<select id=\"{$id}\"
name=\"{$name}\"
class=\"btn
btn-outline-secondary
waves-effect
waves-light
keyword_selector\"
style=\"width:140px;
height: 22px;
float:left;height:35px;
padding: 4px 14px;
{$style}\"
{$flag}>");
if($firstIsDefault){
echo (
"<option value ".isSelected($contents[0], $options).">"
.getName($contents[0], $options).
"</option>");
for($i = 1; $i < count($contents); $i++)
renderOption($contents[$i], $options);
}else{
foreach ($contents as $i => $content)
renderOption($content, $options);
}
echo ("</select>");
}
Using Drop Down(in another php file)
require_once("DropDown.php");
DropDownMenu($customers, [
"id"=>"customer-dropdown",
"name"=>"customer_id",
"firstIsDefault"=> true
]);
DropDownMenu($classes, [
"id"=>"class-dropdown",
"name"=>"class",
"firstIsDefault"=> true,
"style"=>"margin-left:5px;"
]);
# Total 7 times called
Results In
| DropDown | DropDown | 01 DropDown | 0 DropDown | 2345 DropDown | DropDown | DropDown |
Behavior
When I checked the elements in browser, all of the option element were <option value="" selected="">text was different</option>. Where expected behavior is only the first option being selected.
I added variable asdf123 in DropDown.php to look what was happening. And as noted above Results in, is printed in the sequence of 0 1 0 2 3 4 5.
Why would this happen? Are PHP functions asynchronous? What is happening? What could be the cause?
EDIT: I have fixed all of the options were selected part. It was because I was using the key in the $contents were wrong. Instead of "value" I used "id". But I still don't know why the execution sequence was messed up.
$customers=[[value=>a,name=>aa], [value=>b,name=>bb], [value=>c,name=>cc]]; // needed to tests
$classes=[[value=>A,name=>AA], [value=>B,name=>BB], [value=>C,name=>CC]]; // needed to tests
$asdf123 = 0;
function getValue($content, $options){ return ($options[valueByName]) ? $content : $content[value];}
function getName($content, $options){ return ($options[valueByName]) ? $content : $content[name];}
function isSelected($content, $options){ return (getValue($content, $options) == $options[selected]) ? ' selected' : '';}
function renderOption($content, $options){ echo '<option value="'.getValue($content, $options)."\"".isSelected($content, $options).">".getName($content, $options)."</option>\r\n"; }
function DropDownMenu($contents, $options){
echo $GLOBALS[asdf123]++."\r\n";
foreach([id, name, style, flag, firstIsDefault] as $val){ $$val = $options[$val];}
echo "<select id=\"$id\" name=\"$name\" \r\n class=\"btn btn-outline-secondary waves-effect waves-light keyword_selector\"\r\n style=\"width: 140px; height: 22px; float: left; height: 35px; padding: 4px 14px; \r\n $style\" \r\n $flag>\r\n";
if($firstIsDefault){
echo '<option value=""'.isSelected($contents[0], $options).'>'.getName($contents[0], $options)."</option>\r\n"; // lost ' ="value" ' , ' " ' , html syntax!!!!
$j = count($contents); // don't count every time
for($i = 1; $i <= $j; $i++){ renderOption($contents[$i], $options);} } // $i < $j is incomplete
else{ foreach ($contents as $key => $content) renderOption($content, $options);}
echo "</select>\r\n";}
DropDownMenu($customers, [id=>'customer-dropdown', name=>customer_id, firstIsDefault=> 1]);
DropDownMenu($classes, [id=>'class-dropdown', name=>'class', firstIsDefault=> true, style=>'margin-left:5px;']);
Just clean up, fix html and css syntax, fill empty values and will work fine.
Selected is only last option - as you set it.
... that's not pretty code, you know?
For html, css use Validator, please

Extract value from array then run if on value

I have an array of items (cheese) in a checkbox format like so
array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),
The values of the array are displayed on a page (in a hidden div) using the heredoc declaration with an if to check if the checkbox has been used - if the return is empty the div does not show - if one of the checkboxes is "checked" then it does.
///Cheese selections
if (!empty($cheesbox)) {
$output .= <<< OUTPUT
<br />
<div class="sides">Comes with: <p>{$cheesebox}</p></div>
<br />
OUTPUT4;
}
What I need to do is pull any one of the values in the array and if its in the $cheesebox the do something.
Ive tried using an ifelse like this
if ( ('$cheesebox') == "Cheddar" ){
echo "Your topping is Cheddar";
}
elseif ( ('$cheesebox') == "Gouda" ){
{
echo "Your topping is Gouda";
}
elseif ( ('$cheesebox') == "Bleu" ){
{
echo "Your topping is Bleu";
}
however this does not work - I'm sure I have it wrong somehere along the line or does the heredoc function only allow for one?
if so is there a way to accomplish this?
Single quotes in PHP mean a literal string with no parsing of variables. Try this:
if ($cheesebox == "Cheddar") {
echo "Your topping is Cheddar";
} else if ($cheesebox == "Gouda") {
echo "Your topping is Gouda";
} else if ($cheesebox == "Bleu") {
echo "Your topping is Bleu";
}
Better yet:
if (in_array($cheesebox, ['Cheddar', 'Gouda', 'Bleu'])) {
echo "Your topping is {$cheesebox}";
}
EDIT: In response to your further requirements in the comments:
In your PHP:
$cheeses = ['Cheddar', 'Gouda', 'Bleu'];
$cheeseBoxes = '';
foreach ($cheeses as $cheese) {
$cheeseClass = $cheesebox == $cheese ? '' : 'cheese-hidden';
$cheeseBoxes .= <<<CHEESE
<div class="cheese {$cheeseClass}">
<p>Cheese: {$cheese}</p>
<img src="/images/cheeses/{$cheese}.png" alt="A picture of some {$cheese}" />
</div>
CHEESE;
}
// Then, wherever you need it, or just use $cheeseBoxes in your chosen heredoc:
echo $cheeseBoxes;
In your CSS, to hide the inactive ones:
.cheese.cheese-hidden {
display: none;
}

Controllable table fields in PHP/HTML

Im creating a website where there are table (10x10) with adverts inside (pictures+links). I created this table and created one advert, which leads to testlink.com and has picture "img100x100.png". How could i change the code, so I can get different links and images for each table data cell? Please explain as much as possible, because I have just started to learn PHP & MySQL.
I currently have the following code in index.php:
<?php include 'header.php'; ?>
<body>
<?php
$rows_max = 10;
$columns_max = 10;
$links = Array(
'link' => "http://testlink.com",
'image' => "img100x100.png");
print '<table border="1px" style="border-collapse:collapse;">';
for($row = 1; $row <= $rows_max; $row++)
{
print '<tr>';
for($col = 1; $col <= $columns_max; $col++)
{
print '<td width="10px" height="10px" background="'.$links["image"].'" >';
print '<center> </center>';
print '</td>';
}
print '</tr>';
}
print '</table>';
include 'footer.php'; ?>
and
td a
{
width: 100%;
height: 100%;
display: block;
margin-top: 0px auto;
}
Well you could link this up to a database with 10 rows and foreach through those. Or even simpler, you could have this all in an array. It would be a lot easier if you didn't use a table and just made them square with CSS and floated them left in a container. You would get a similar result.
$links = array(
array(
'url' => 'http://link.com/',
'image' => 'image.jpg'
), array(
'url' => 'http://link.com/',
'image' => 'image.jpg'
), array(
'url' => 'http://link.com/',
'image' => 'image.jpg'
)
// etc
);
Then
foreach($links as $link){
// Code to build out a cell
echo $link['url'];
echo $link['image'];
}

PHP navigation with $_GET method ignoring css active class [duplicate]

This question already has answers here:
how to add active to a tag and li tag with php
(5 answers)
Closed 8 years ago.
My hover links work as well as the navigation, but the active link will not come on.
My CSS active:
#header ul li a.active,
#header ul li a.active:hover {
color:#fff;
background:#000;
font-weight:bold;
Here is my nav.php file:
<ul>
<?php
$pages = array(
"index.php?p=home" => "Home",
"index.php?p=contact" => "Contact Us",
"index.php?p=services" => "Services",
"index.php?p=employees" => "Employees",
"index.php?p=dashboard" => "Dashboard");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if (preg_match("/$p/",$url)) {
echo "class='active'";
}
echo '><a href=', "$url", '>', "$label", '</a></li>';
}
?>
</ul>
This is my method inside of the index page retrieving each page:
<?php
if (file_exists("pages/$p.php")) {
include("pages/$p.php");
}else{
include("pages/home.php");
}
?>
I suppose that you are using urls like: /index.php?p=page_name
<ul>
<?php
$pages = array(
"home" => "Home",
"contact" => "Contact Us",
"services" => "Services",
"employees" => "Employees",
"dashboard" => "Dashboard");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if ($p == $url) {
echo "class='active'";
}
echo '>' . $label . '</li>';
}
?>
</ul>

Display foreach array side-by-side with CSS

I am pretty sure that if I use something like this in css
#list {
float:left;
}
I can format the display of my array to look like
A B C
rather than
A
B
C
The problem is I am having problems formatting the php of the with the proper <div>'s to give me what I want.
foreach ( $model->address as $address ) {
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
}
Can someone help me modify the foreach above to achieve the different layout. I also need to be able to format the Address differently then the Name
EDIT: For clarification...
A =
Address
City
B =
Address
City
C =
Address
City
You need to wrap each address in a div and use a class to float it:
PHP/HTML:
foreach ( $model->address as $address ) {
echo '<div class="address-item">';
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
echo '</div>';
}
CSS:
.address-item {
float: left;
}
$out = "<ul>";
foreach($model->address as $address){
if(!isset($address->Address) && !isset($address->city->Name)) continue;
$out .= "<li>" . isset($address->Address) ? $address->Address : "" . " "
. isset($address->city->Name) ? $address->city->Name : "" . "</li>";
}
$out .= "</ul>";
print $out;
CSS
li {
float: left;
}
something like:
foreach ( $model->address as $address ) {
echo '<div class="list">';
if ($address->Address) echo $address->Address.'<br />';
if ($address->city->Name) echo $address->city->Name;
echo '</div>';
}
wherein, the CSS will be:
.list {float:left;}

Categories