I have the following xml file:
row category="1" category_name="CatA" entry_id="1" entry_name="A1"
row category="1" category_name="CatA" entry_id="2" entry_name="A2"
row category="1" category_name="CatA" entry_id="3" entry_name="A3"
row category="2" category_name="CatB" entry_id="4" entry_name="B1"
row category="2" category_name="CatB" entry_id="5" entry_name="B2"
row category="2" category_name="CatB" entry_id="6" entry_name="B3"
row category="3" category_name="CatC" entry_id="7" entry_name="C1"
row category="4" category_name="CatD" entry_id="8" entry_name="D1"
and I want to produce below html:
CatA
----A1
----A2
----A3
CatB
----B1
----B2
----B3
CatC
----C1
CatD
----D1
for this I am using below php xml parser:
$ndeshjet=simplexml_load_file("xml_file.xml");
$new_category = 1;
foreach ($ndeshjet->row as $entry) {
$category = $entry['category'];
if ($category <> $new_category){
$category_name = $entry['category_name'];
echo $category_name."</br>";
$new_category = $category;
} else {
$entry_name = $entry['entry_name'];
echo "----".$entry_name."</br>";
}
}
?>
but the result is :
----A1
----A2
----A3
CatB
CatB
CatB
CatC
CatD
Thanks in advance
As an alternative, you could gather all the values first inside an array and make the category name as key pushing same keys inside. After thats done and gathered, print them accordingly:
$categories = array();
// gather inside container
foreach ($ndeshjet->row as $entry) {
$category_name = (string) $entry->attributes()->category_name;
$entry_name = (string) $entry->attributes()->entry_name;
$categories[$category_name][] = $entry_name;
}
// presentation
foreach($categories as $category_name => $entries) {
echo $category_name . '<br/>';
foreach($entries as $entry) {
echo '----' . $entry . '<br/>';
}
}
Sample Output
Related
I managed to add multiple data in one column in the database, but now I need to display it with a new line in the browser so they don't stick with each other as I display them as an array in one column.
Here is my code:
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subArray = array("StudentAnswer");
$subId6 = $db->get("answertable", null, $subArray);
foreach ($subId6 as $sub) {
$answers[] = $sub['StudentAnswer'] . "\n";
}
foreach ($answers as $row) {
$answers2 = explode("||", $row[0]);
foreach($answers2 as $row2){
$answers3 = $row2 . '\n';
}
}
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers3);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
You are overriding $subId6 after getting its content. Try to fetch the table $rows in a new variable and the extract the content from it, like the code below.
<?php
// Example of $subId6 content
$subId6 = array(["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]], ["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]]);
// Fetch rows
foreach ($subId6 as $sub) {
$rows[] = $sub['StudentAnswer'];
}
// Decode rows
foreach($rows as $row) {
$answers = explode("\n", $row[0]);
echo "New answers: \n";
// Split answers in single answer
foreach ($answers as $answer)
echo "$answer \n";
echo "\n";
}
You will have a list of all the answers split for table rows
If you want a string of answers seperated by a space then simply do
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subId6 = $db->get("answertable");
foreach ($subId6 as $sub) {
$answers .= $sub['StudentAnswer'] . ' ';
}
$answers= rtrim($answers, ' '); //remove last space in case thats an issue later
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}
How to loop all records and display all the respective children using HTML <ul></ul>? I tried using PHP Do While but stuck at only 1 level.
MySQL (select * from user)
Desired output
Tree View
List View
The easy was is to do that with the help of array. Hope it helps.
$data = array();
foreach ($result as $item) {
$key = $item['name']; // or $item['info_id']
if (!isset($data[$key])) {
$data[$key] = array();
}
$data[$key][] = $item;
}
You can use this code:
$aResults; // it is your mysql result (array)
$resultSorted = array();
$resultSorted = recursiveList($aResults, '');
function recursiveList(&$aResults, $iKey)
{
$aChilds = '<ul>';
foreach ($aResults as $iLoopKey => $aResult) {
if ($aResult['parent'] == $iKey) {
unset($aResults[$iLoopKey]);
$aChilds .= '<li>' . $aResult['name'] . '</li>';
$aChilds .= recursiveList($aResults, $aResult['name']);
}
}
return $aChilds . '</ul>';
}
// Output example
echo '<pre>';
print_r($resultSorted);
As a result, I recived:
Also you'd better use 'parent_id' instead 'parent' in yours tables.
I have array with already existing values:
$existingValues = array();
now i get new values in xml file (is a import script) but i have to avoid insert of already existing values, my question is, how can i do a if check in foreach where i list all new values from xml?
$i = 1;
foreach($node->children() as $child) :
$attribute2 = $child->attributes();
$productcode = $attribute2['sku'];
$productvariant = $attribute2['variantid'];
$productprice = $attribute2['price'];
if ($attribute2['sku']) :
echo $productcode . ' - ' . $productvariant . '<br>';
endif;
$i++;
endforeach;
I tried with in_array() but it's not correct.
You can create an array wich stores the products and test if the current product is already in the array:
$i = 1;
$products = array();
foreach($node->children() as $child) :
$attribute2 = $child->attributes();
$productcode = $attribute2['sku'];
$productvariant = $attribute2['variantid'];
$productprice = $attribute2['price'];
if ($attribute2['sku'] && !in_array($productcode, $products)) :
echo $productcode . ' - ' . $productvariant . '<br>';
endif;
$products[] = $productcode;
$i++;
endforeach;
You can create a $existingSKU array, extracting sku from existing elements. Then you can compare current sku with existing, and if not present, you can add element to existing.
// build existing sku array
$existingSKU = array();
foreach($existingValues as $value)
{
array_push($existingSKU, $value['sku']);
}
// add element to existing, if not present
foreach($node->children() as $child)
{
$attribute2 = $child->attributes();
if(!in_array($attribute2['sku'], $existingSKU))
{
array_push($existingValues, $attribute2);
}
}
Since you don't use it, you can remove $i.
Following function arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
function buildHtmlList($array)
{
$maxlevel = 0;
foreach ($array as $key => $value)
{
$previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
$nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;
if ($value['parent'] != $previousparent)
{
echo "\n<ul>";
++$maxlevel;
}
echo "\n<li>" . $value['name'];
if ($nextparent == $value['parent'])
echo "</li>";
}
for ($i = 0; $i < $maxlevel; ++$i)
{
echo "\n</li>\n</ul>";
}
}
It arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
The wrong piece is the whole logic of the function. You treat the array as a flat list (as it is!), however, you'd like to display a tree.
As a flat list can't be displayed as a tree, you need to change the flat list to a tree first and then write a function that displays a tree.
An example how to convert a flat array to a tree/multidimensional one is available in a previous answer.
Try something like this (where $array is formatted like your example):
$corrected_array = array();
// This loop groups all of your entries by their parent
foreach( $array as $row)
{
$corrected_array[ $row['parent'] ][] = $row['name'];
}
// This loop outputs the children of each parent
foreach( $corrected_array as $parent => $children)
{
echo '<ul>';
foreach( $children as $child)
{
echo '<li>' . $child . '</li>';
}
echo '</ul>';
}
Demo