How to show all XML Attribute values thru PHP Foreach - php

I am using this code and i am just getting 1 Sports data not all and its just repeating 1 Odds data . Please check
<?php
$xml = simplexml_load_file('demo.xml');
foreach($xml->Game->children() as $a => $b) {
echo $b['Name'].$b['ID'].'<br>';
foreach($xml->Game->SportsBook->children() as $c => $d) {
echo $d['LineType'].$d['LastUpdated'].'<br>';
}
}
print_r($xml->Game->SportsBook)
?>

I think you were having problems understanding the nesting of the data, I think this will give you a better starting point...
foreach($xml->Game->SportsBook as $d) {
echo $d['Name'].' '.$d['ID'].'<br>';
foreach( $d->Odds as $odds) {
echo $odds['LineType'].' '.$odds['LastUpdated']."\n";
}
}

Related

Using PHP Foreach with 3 Arrays

I'm getting data from a site as you can see in the code below. Is it possible to use 3 arrays in a single foreach loop?
I've tried too many code snippets, but I haven't found the solution.
This is my normal code:
<?php
$i = 0;
$url = file_get_contents("xxx");
$display = '#{"__typename":"GraphImage","id":"(.*?)","edge_media_to_caption":{"edges":\[{"node":{"text":"(.*?)"}}]},"shortcode":"(.*?)","edge_media_to_comment":{"count":(.*?)},"comments_disabled":(.*?),"taken_at_timestamp":(.*?),"dimensions":{"height":(.*?),"width":(.*?)},"display_url":"(.*?)","edge_liked_by":{"count":(.*?)},"edge_media_preview_like":{"count":(.*?)},"location":(.*?),"gating_info":(.*?),"media_preview":"(.*?)","owner":{"id":"(.*?)","username":"(.*?)"}#i';
preg_match_all($display, $url, $dop);
foreach ($dop[1] as $displayop1) {
echo $displayop1."<p>";
}
foreach ($dop[9] as $displayop2) {
echo $displayop2."<p>";
}
foreach ($dop[15] as $displayop3) {
$i++;
if($i == 2) {break;}
echo $displayop3."<p>";
}
I've tried.
<?php
foreach ($dop[1] as $displayop1) {
foreach ($dop[9] as $displayop2) {
foreach ($dop[15] as $displayop3) {
echo $displayop1 . "<p>";
echo $displayop2 . "<p>";
$i++;
if ($i == 2) {
break;
}
echo $displayop3 . "<p>";
}
}
}
?>
<?php
foreach (array_combine($dop[1], $dop[9], $dop[15]) as $dop1 => $dop2 => $dop3) {
echo $dop1.$dop2.$dop3;
}
?>
These codes didn't work.
Can someone help me do this? I searched the solution a lot, but I couldn't find any information. I didn't know exactly how to search on the internet because my English isn't very good, thank you.
Closest option I see to a single loop is 2:
for($i=1; $i < 15; $i++) {
//you can do a if statement here if you need 1 9 and 15 respectivley
foreach ($dop[$i] as $displayop) {
}
}

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.

return array_chunk in groups

I can usually do pretty decent with basic arrays, but this one has put my head vs the wall.
I am trying to pass some information (for a menu) through a function, and return it in a formatted fashion.
My desired end result is to send some information like this. I need to be able to repeat the array until it is empty in the event that I have a number of fields
$Sort = array('imgup.jpg','imagedn.jpg','Name','imgx.jpg','imagy.jpg','Name4');
NewSortBox($Sort);
and have an end result that would return like
<div>Name <img src='imgup.jpg'><img src='imgdn.jpg'></div>
<div>Name4 <img src='imgx.jpg'><img src='imgy.jpg'></div>
I have figured out that I have to use the Array_Chunk function to break the array, but I am not able to figure out how to make it properly use the foreach or loop functions.
function NewSortBox(&$array){
$newArray = array_chunk($array, 3, false);
$i = 0;
foreach ($newArray as $inner_array) {
$i++;
echo "<div>";
while (list($key, $value) = each($inner_array)) {
echo "$key: $value";
// Here is where I am totally lost, I want to acheive something like ??
// echo "$value[1] <img src='$value[2]'><img src='$value[3]'>";
}
echo "</div>";
}
Something like this may help to get the desired result:
$newArray = array_chunk($Sort, 3, false);
foreach ($newArray as $inner_array) {
echo "<div>";
list($a, $b, $c) = $inner_array;
echo $c.":".$b.":".$a; //arrange the variables as required
echo "</div>";
}

PHP Nested loops where values are the key to the next level of the array

I'm relatively new to PHP and I hope you can help me solve my problem. I am selecting out data from a database into an array for timekeeping. Ultimately, I would like to calculate the total number of hours spent on a project for a given customer.
Here is the code to populate a multi-dimensional array:
...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
I would now like to iterate over $mArray to generate an xml file like this:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
This nested foreach doesn't work. Can someone give me a couple of tips on how to traverse this structure? Thank you for reading!
UPDATE:
Based on the comments I've received so far (and THANK YOU TO ALL), I have:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
This is now only providing a single iteration (one row of data).
Foreach syntax is foreach($array as $value). You're trying to use those values as array keys, but they're not values - they're the child arrays. What you want is either:
foreach($mArray as $username) {
foreach($username as ...)
or
foreach($mArray as $key => $user) {
foreach($mArray[$key] as ...)

Parent-child navigation generation from tree array in PHP

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

Categories