PHP nested array into HTML list - php

Trying to get to grips with PHP, but I have absolutely no idea how to do this.
I want to take this array:
$things = array('vehicle' => array('car' => array('hatchback', 'saloon'),'van','lorry'),
'person' => array('male', 'female'),
'matter' => array('solid', 'liquid', 'gas'),
);
and turn it into this into something like this in HTML:
Vehicle
Car
Hatchback
Saloon
Van
Lorry
Person
Male
Female
Matter
Solid
Liquid
Gas
Tried a number of solutions from searching, but cannot get anything to work at all.

What you are looking for is called Recursion. Below is a recursive function that calls itself if the value of the array key is also an array.
function printArrayList($array)
{
echo "<ul>";
foreach($array as $k => $v) {
if (is_array($v)) {
echo "<li>" . $k . "</li>";
printArrayList($v);
continue;
}
echo "<li>" . $v . "</li>";
}
echo "</ul>";
}

Try something like:
<?php
function ToUl($input){
echo "<ul>";
$oldvalue = null;
foreach($input as $value){
if($oldvalue != null && !is_array($value))
echo "</li>";
if(is_array($value)){
ToUl($value);
}else
echo "<li>" + $value;
$oldvalue = $value;
}
if($oldvalue != null)
echo "</li>";
echo "</ul>";
}
?>
Code source: Multidimensional array to HTML unordered list

Related

PHP displaying arrays having duplicate with color=red [duplicate]

This question already has answers here:
PHP highlight duplicate values in array [duplicate]
(2 answers)
Closed last month.
I have a array that i want to check if has duplicates using PHP
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
I was able to achieve it by using below function
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $i) {
if(in_array($i,$processed)) {
$duplicates[]=$i;
} else {
$processed[]=$i;
}
}
return $duplicates;
}
I got below output
Array ( [0] => Two [1] => Five )
Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table.
My goal is to display the duplicated values with red font color.
Try this piece of code... simplest and shortest :)
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$arrayValueCounts = array_count_values($i);
foreach($i as $value){
if($arrayValueCounts[$value]>1){
echo '<span style="color:red">'.$value.'</span>';
}
else{
echo '<span>'.$value.'</span>';
}
}
Here is optimized way that will print exact expected output.
<?php
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$dups = array_count_values($i);
print_r($dups);
foreach($i as $v)
{
$colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : '';
echo "<span $colorStyle>$v</span>";
}
?>
Try this,
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $key => $i) {
if(in_array($i,$processed)) {
$duplicates[$key]=$i; // fetching only duplicates here and its key and value
}
}
return $duplicates;
}
foreach($processed as $k => $V){
if(!empty($duplicates[$k])){ // if duplicate found then red
echo '<span style="color:red">'.$duplicates[$k].'</span>';
}else{
echo '<span>'.$duplicates[$k].'</span>'; // normal string
}
}
Like this :
PHP
function array_duplicate_css($input) {
$output = $processed = array();
foreach($input as $key => $i) {
$output[$key]['value'] = $i;
if(in_array($i, $processed)) {
$output[$key]['class'] = 'duplicate';
} else {
$output[$key]['class'] = '';
$processed[] = $i;
}
}
return $output;
}
foreach(array_duplicate_css($input) as $row) {
echo '<tr><td class="' . $row['class'] . '">' . $row['value'] . '</td></tr>';
}
CSS
.duplicate {
color: #ff0000;
}
Simple use array_count_values.
$array=array('One','Two','Two','Three','Four','Five','Five','Six');
$new_array= array_count_values($array);
foreach($new_array as $key=>$val){
if($val>1){
for($j=0;$j<$val;$j++){
echo "<span style='color:red'>".$key."</span>";
}
}else{
echo "<span>".$key."</span>";
}
}
It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.

traversing an array in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop an array of array
So I know how to traverse an array of even key => value (associative), but I have a weird array where I need to walk through it and print out values:
$object_array = array(
'type' => 'I am type',
array(
'property' => 'value',
'property_2' => 'value_2'
)
);
What I thought I could do is:
foreach($object as $key=>$vlaue){
//what now?
}
So as you can see I am lost, how do I walk through the next array?
You can try:
function traverse($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
traverse($array);
continue;
}
echo $value;
}
}
foreach($object as $key=>$value){
if( is_array($value) ) {
foreach($value as $key2=>$value2) {
//stuff happens
}
} else {
//other stuff
]
}
Try:
foreach($object_array as $value) {
if(!is_array($value))
echo $value;
else {
foreach($value as $m)
echo $m;
}
}
Manual for foreach
In your for loop you could do:
if(is_array($object[$key]))
//process inner array here
It depends on how deep your arrays go, if you have arrays of arrays of arrays...and so on, a different method would be better, but if you just have one level this is a pretty simple way of doing it.
Well, you could do something like this:
foreach($object_array as $key=>$value)
{
if(is_array($value) {
foreach($value as $k=>$v) {
echo $k." - ".$v;
}
} else {
echo $key." - ".$value;
}
}
An alternative with array_walk_recursive():
function mydebug($value, $key) {
echo $key . ' => ' . $value . PHP_EOL;
}
array_walk_recursive($object_array, 'mydebug');
Handy if you doing something simple with the values (e.g. just echo ing).

PHP Merge Similar Objects In A Multidimensional Array

I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}

PHP — How to determine number of parents of a child array?

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";
}

echo key and value of an array without and with loop

This is an array i have
<?php
$page['Home']='index.html';
$page['Service']='services.html';
?>
How do i get to echo something like this for individual one like
Home is at index.html
and again how can i do this through a loop and echo all?
foreach($page as $key => $value) {
echo "$key is at $value";
}
For 'without loop' version I'll just ask "why?"
Without a loop, just for the kicks of it...
You can either convert the array to a non-associative one, by doing:
$page = array_values($page);
And then acessing each element by it's zero-based index:
echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'
Or you can use a slightly more complicated version:
$value = array_slice($page, 0, 1);
echo key($value); // Home
echo current($value); // index.html
$value = array_slice($page, 1, 1);
echo key($value); // Service
echo current($value); // services.html
If you must not use a loop (why?), you could use array_walk,
function printer($v, $k) {
echo "$k is at $v\n";
}
array_walk($page, "printer");
See http://www.ideone.com/aV5X6.
Echo key and value of an array without and with loop
$array = array(
'kk6NFKK'=>'name',
'nnbDDD'=>'claGg',
'nnbDDD'=>'kaoOPOP',
'nnbDDD'=>'JWIDE4',
'nnbDDD'=>'lopO'
);
print_r(each($array));
Output
Array
(
[1] => name
[value] => name
[0] => kk6NFKK
[key] => kk6NFKK
)
for the first question
$key = 'Home';
echo $key." is at ".$page[$key];
function displayArrayValue($array,$key) {
if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
}
displayArrayValue($page, "Service");
How to echo key and value of an array without and with loop
$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];
My version without a loop would be like this:
echo implode(
"\n",
array_map(
function ($k, $v) {
return "$k is at $v";
},
array_keys($page),
array_values($page)
)
);
array_walk($v, function(&$value, $key) {
echo $key . '--'. $value;
});
Learn more about array_walk
A recursive function for a change;) I use it to output the media information for videos etc elements of which can use nested array / attributes.
function custom_print_array($arr = array()) {
$output = '';
foreach($arr as $key => $val) {
if(is_array($val)){
$output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong><ul class="children">' . custom_print_array($val) . '</ul>' . '</li>';
}
else {
$output .= '<li><strong>' . ucwords(str_replace('_',' ', $key)) . ':</strong> ' . $val . '</li>';
}
}
return $output;
}
You can try following code:
foreach ($arry as $key => $value)
{
echo $key;
foreach ($value as $val)
{
echo $val;
}
}

Categories