Get Parent Value and Combine To Child Value Using Loop - php

i have data and want to modify the result using parent and child method. As an example below.
I try with following code but have no luck because the last iteration give wrong result as seen on screenshot below, Is there any idea how to solve it?? live code here https://paiza.io/projects/vS4BHo0mMrKiJZoPpMoNvQ
<?php
$data = array("022.04.GA", "4660", "4660.CBD", "4660.CBD.002", "52", "A", "533111", "022.04.WA", "4631", "4631.EAF", "4631.EAF.001", "51", "B", "524111", "524113", "52", "C", "521211", "524113", "4631.EAH", "4631.EAH.001", "51", "B", "521211", "522131", "4634", "4634.EAG", "4634.EAG.001", "51", "C", "521219", "522191");
echo "<table>";
echo "<tr>";
echo "<td>Code</td><td>Result</td>";
foreach($data as $item)
{
$length = strlen($item);
$data = '';
if($length==9) {
$value = $item;
} elseif($length==4) {
$value .= $data.'.'.$item;
} elseif($length==8) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==12) {
$output = substr($item,-4);
$value .= $data.$output;
} elseif($length==3) {
$value .= $data.'.'.$item;
} elseif($length==1 or $length==2) {
$value .= $data.'.'.$item;
} else {
$value .= $data.'.'.$item;
}
echo "<tr>";
echo "<td>$item</td>";
echo "<td>$value</td>";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
?>

Related

Outputting manual JSON in PHP

I am building some JSON myself like so:
echo '{ "type": "root",';
echo '"children" : [';
echo '{';
echo '"identifier": "Contractor",';
echo '"title": "Contractor",';
echo '"autoIdentifier": true,';
echo '"options": [';
foreach ($names as $n){
echo '{';
echo '"text": '.'"'.$n['name'].'",';
echo '"identifier": '.'"'.$n['id'].'"';
echo '},';
}
echo '],';
echo '"title": "TEST",';
echo '"description": ""';
echo '}';
As you can see i am looping through some data to print into the JSON output. The problem i am having is the last echo within the loop. This is because it currently has a comma after the bracket.
However if it is the last element within my data loop, i want the comma to be removed so that it creates proper JSON.
How can i achieve this? With some kind of counter and then an if statement?
$names = array_map(function($name) {
return '{ "text":"' . $name['name'] . '", "identifier":"' . $name['id'] . '" }';
}, $names);
echo '{ "type": "root",';
echo '"children" : [';
echo '{';
echo '"identifier": "Contractor",';
echo '"title": "Contractor",';
echo '"autoIdentifier": true,';
echo '"options": [';
echo implode(',', $names);
echo '],';
echo '"title": "TEST",';
echo '"description": ""';
echo '}';
I'd seriously prefer just using PHPs JSON encoding features, json_encode. For example, what if the $n["name"] had a quote in it? Your JSON would be invalid, but if you used json_encode, it'd take care of that.
$child = [
"identifier" => "Contractor",
"autoIdentifier" => true,
"options" => [],
"title" => "TEST",
"description" => ""
];
foreach ($names as $n)
{
$child["options"][] = [
"text" => $n["name"],
"identifier" => $n["id"]
];
}
header( "Content-Type: application/json" );
echo json_encode( ["type" => "root", "children" => [$child]] );
change your loop to:
$var = '';
foreach ($names as $n){
$var .= '{';
$var .= '"text": "'.$n['name'].'",';
$var .= '"identifier": "'.$n['id'].'"';
$var .= '} ,';
}
$var = rtrim($var,",");
echo $var;
OR
change your code like this:
$var = '{ "type": "root","children" : [{"identifier": "Contractor","title": "Contractor","autoIdentifier": true,"options": [';
foreach ($names as $n){
$var .= '{"text": "'.$n["name"].'","identifier": "'.$n["id"].'"} ,';
}
$var = rtrim($var,",");
$var = '],"title": "TEST","description": ""}';
echo $var;

JSON encode to create a table

How can I eventually put the following code into a table or viewable format.
$query =
"SELECT title, descr FROM details";
$result = mysqli_query($connection,$query);
$details = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($details, $row);
}
echo json_encode($details);
No need to json encode the result, however with making tables I like to make a json template file to dictate how the table should be constructed so that I can make changes easily.
// this would normally be located elsewhere.
$templateJson = '"columns": {
"title":{
"title": "Title",
"class": "title"
},
"descr":{
"title": "Description",
"class": "descr"
}
}';
$template = json_decode($templateJson);
if(is_array($details))
{
$markup = "<table><thead><tr>";
foreach($template["columns"] as $col=>$format)
{
$markup .= '<th class="'.$format['class'].'">';
$markup .= $format['title'];
$markup .= '</th>';
}
$markup .= "</tr></thead><tbody>";
foreach($details as $i=>$row)
{
$markup .= '<tr>';
foreach($template as $col=>$format)
{
$markup .= '<td>'.$row[$col].'</td>';
}
$markup .= '</tr>';
}
$markup .= "</tbody></table>";
}
echo $markup;
I tend to do way more loops than I probably should though, there may be a more optimal way but this will give you valid table markup.

Php Multidimensional array for navigation

Needed Navigation Html
Home
Pages
About
Services
Products
Contact
FAQs
Sitemap
Privacy Policy
Column Layouts
1 Column
2 Column (Left Sidebar)
2 Column (Right Sidebar)
3 Column
4 Column
I want to use php arrays and foreach loops to output the needed html.
The php code I have thus far is:
<?php
$data = array("navigation");
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
echo '<ul>';
foreach($data as $nav) {
foreach($nav as $subNavKey => $subNavHref) {
echo "<li><a href='$subNavHref'>$subNavKey</a>";
}
}
echo '</ul>';
?>
I was thinking I would need three foreach loops nested but php warnings/errors are generated when the third loop is reached on lines such as:
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
I'm not quite sure how to test for 3rd level depths such as:
$data['navigation']['Pages']['About'] = base_url('pages/about');
Also, outputting the needed li and ul tags in the proper positions has given me trouble aswell.
Use recursion
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
$data['navigation']['Pages']['About']['Team'] = base_url('pages/team');
$data['navigation']['Pages']['About']['Team']['Nate'] = base_url('pages/nate');
echo "<ul>"
print_list($data);
echo "</ul>"
function print_list($menu) {
foreach($menu as $key=>$item) {
echo "<li>";
if(is_array($item)) {
echo "<ul>";
print_list($item);
echo "</ul>";
} else {
echo "<a href='{$val}'>$key</a>";
}
echo "</li>";
}
}
<?php
function nav($data) {
$html = '<ul>';
foreach ($data as $k => $v) {
if (is_array($v)) {
$html .= "<li>$k" . nav($v) . "</li>";
}
else {
$html .= "<li><a href='$k'>$v</a>";
}
}
$html .= '</ul>';
return $html;
}
echo nav($data);
A recursive function can get the job done:
$items = array(
"Home",
"Pages" => array(
"About",
"Services",
"Products",
"Contact",
"FAQs",
"Sitemap",
"Privacy Policy",
"Column Layouts" => array(
"1 Column",
"2 Column (Left Sidebar)",
"2 Column (Right Sidebar)",
"3 Column",
"4 Column"
)
)
);
function getMenu($array) {
foreach($array as $key => $value) {
if(is_array($value)) {
echo "<li>" . $key . "</li>";
echo "<ul>";
getMenu($value);
echo "</ul>";
} else {
echo "<li>" . $value . "</li>";
}
}
}
echo "<ul>";
getMenu($items);
echo "</ul>";
Output:
You should use a recursive function, for example (Working Demo):
function makeMenu($array)
{
$menu = '';
foreach($array as $key => $value) {
if(is_array($value)) {
$menu .= '<li>' . $key . '<ul>' . makeMenu($value) . '</ul></li>';
}
else {
$menu .= "<li><a href='". $value ."'>" . $value ."</a></li>";
}
}
return $menu;
}
Then call it like:
$data = array(
"Home",
"Pages" => array("About", "Services"),
"Column Layouts" => array("1 Column", "2 Column (Left Sidebar)")
);
echo '<ul>' . makeMenu($data) . '</ul>';

Output each mongodb record to an html table

I'm building an app which pulls records from a MongoDB. I've built the thead>tr>th as follows:
// building table head with keys
$cursor = $collection->find();
$array = iterator_to_array($cursor);
$keys = array();
foreach ($array as $k => $v) {
foreach ($v as $a => $b) {
$keys[] = $a;
}
}
$keys = array_values(array_unique($keys));
// assuming first key is MongoID so skipping it
foreach (array_slice($keys,1) as $key => $value) {
echo "<th>" . $value . "</th>";
}
This gives me:
<thead>
<tr>
<th>name</th>
<th>address</th>
<th>city</th>
</tr>
</thead>
This works very well, it grabs all the keys and builds the table head. I don't have to specify anything and the thead is built dynamically from the data. The part I'm unable to figure out is building all of the tr>td's
I can easily grab the info and build it like this:
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
echo "<td>" . $venue['name'] . "</td>";
echo "<td>" . $venue['address'] . "</td>";
echo "<td>" . $venue['city'] . "</td>";
echo "</tr>";
}
Doing so requires me to modify my php every time I add a new field. How can I build the tr>td's automagically based on the data from mongodb like I am with the thead?
My data looks like this:
{
"name": "Some Venue",
"address": "1234 Anywhere Dr.",
"city": "Some City"
}
Have you try to use second foreach as below
$cursor = $collection->find();
$cursor_count = $cursor->count();
foreach ($cursor as $venue) {
echo "<tr>";
foreach (array_slice($keys,1) as $key => $value) {
echo "<td>" . $venue[$value] . "</td>";
}
echo "</tr>";
}

PHP - How do I read all attributes of XML items using simpleXML?

I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:
$xml = simplexml_load_file("path/to/file.xml");
showTree($xml->children(), 0);
function showTree($value, $i) {
if($value == '') {
foreach($value as $name2 => $value2) {
echo str_repeat('--', $i)." <$name2> \n";
showTree($value2, ($i+1));
echo str_repeat('--', $i)." </$name2> \n";
}
} else { echo str_repeat('--', $i)." ".trim($value)."\n"; }
} // end: function
As I said, it works fine, but doesn't display the attributes, for example:
<item id=2>Item</item>
returns only the:
<item>Item</item>
Thanks for any responses, Mike.
Unless I missread your code something like this should probably be about right.
$xml = simplexml_load_file("path/to/file.xml");
showTree($xml->children(), 0);
function showTree($value, $i) {
if($value == '') {
foreach($value as $name2 => $value2) {
$attribsStr = '';
foreach($value2->attributes() as $attribName => $attribValue) {
$attribsStr .= $attribName . '="' . $attribValue . '"' . ' ';
}
echo str_repeat('--', $i)." <$name2 $attribsStr> \n";
showTree($value2, ($i+1));
echo str_repeat('--', $i)." </$name2> \n";
}
} else { echo str_repeat('--', $i)." ".trim($value)."\n"; }
} // end: function
Have a look at http://php.net/manual/en/simplexmlelement.attributes.php

Categories