Objects in Objects, Skip one in foreach - php

I'm trying to loop over each object and show the team name on a website... however I want to skip the $variable->active key.
The number of teams varies...How can I skip the 'active' key?
I tried this but it doesn't seem to work:
$active = $team->active;
if (isset($team->active)) {
foreach ($team as $data) {
if (isset($data->idteam) != $active) {
print_r($data);
$return .= '<li><i class="fa fa-power-off"></i> ' . $data->nameteam . '</li>';
} else {
$return .= "No Teams!";
}
}
}
Here is my object:
teamAccess Object
(
[2] => Team Object
(
[nameteam] => Team 1
[idteam] => 2
[enabled] => 1
[last_access_stamp] => 1399603014
[create_stamp] => 4
[update_stamp] => 1399167351
)
[1] => Team Object
(
[nameteam] => Test Team
[idteam] => 1
[enabled] => 0
[last_access_stamp] => 1399603014
[create_stamp] => 0
[update_stamp] => 0
)
[3] => Team Object
(
[nameteam] => Team 3
[idteam] => 3
[enabled] => 1
[last_access_stamp] => 1399603014
[create_stamp] => 0
[update_stamp] => 0
)
[active] => 3
[alerts] => Array
(
)
)

In the foreach, you can capture the key, and check it in a condition to skip it:
foreach ($team as $key => $data) {
if ($key != 'active') {
$return .= '<li><i class="fa fa-power-off"></i> ' . $data->nameteam . '</li>';
}
}
Observation: it seems that the teamAccess object should have a teams property, which could be an array of team objects. This might be a better structure than having all of the data mixed together as root properties.

Related

How to break out of nested foreach loop and enter another foreach loop array?

I'm struggling trying to break out of this nested foreach loop.
If you take a look at my data, I'm trying to go within the team info array, find out what the team ID number is and once I know that ID number, I want to break out of the team array and go into the stats array for that particular ID(team) so I can get each statistic.
The data I'm using updates every week according to each team's rank, so the ID is the only way to know for sure the team you are looking up.
I have the following code so far and can get the team ID number but like I said I want to break out of the team array with the ID number and go into the stats array for that particular ID. Also, this data is for every NFL team and is very long, so I only posted what I could for the array so you get the idea and my foreach loop is below.
Any help is very much appreciated!!!
Array:
Array(
[overallteamstandings] => Array
(
[lastUpdatedOn] => 2019-12-13 4:03:05 AM
[teamstandingsentry] => Array
(
[0] => Array
(
[team] => Array
(
[ID] => 56
[City] => Baltimore
[Name] => Ravens
[Abbreviation] => BAL
)
[rank] => 1
[stats] => Array
(
[GamesPlayed] => Array
(
[#abbreviation] => G
[#text] => 14
)
[PassAttempts] => Array
(
[#category] => Passing
[#abbreviation] => Att
[#text] => 384
)
[PassCompletions] => Array
(
[#category] => Passing
[#abbreviation] => Comp
[#text] => 255
)
[PassPct] => Array
(
[#category] => Passing
[#abbreviation] => Pct
[#text] => 66.4
)
[PassGrossYards] => Array
(
[#category] => Passing
[#abbreviation] => Yds
[#text] => 3016
)
Foreach Loop:
foreach ($response as $overallteamstandings => $b) {
foreach ($b['teamstandingsentry'] as $key => $d) {
//if ($key == '9'){
foreach ($d as $cat => $info) {
if ($cat == 'team') {
foreach ($info as $c => $v) {
if ($c == 'ID') {
echo $v;
if ($v == '59') {
//break 4;
}
}
}
}
if ($cat == 'stats') {
foreach ($info as $category => $stats) {
if ($category == 'Wins') {
foreach ($stats as $val => $value) {
if ($val == '#text') {
echo $value . "-";
}
}
}
if ($category == 'Losses') {
foreach ($stats as $val => $value) {
if ($val == '#text') {
echo $value;
}
}
}
}
}
}
//}
}
}
Here are some functions that might make your life easier. The first returns the ID value for a team based on its name or city. The second returns the stats array for team based on its ID value. All functions return false if they can't find a matching value.
// get a team's id based on its name or city
function get_team_id($response, $team, $type) {
$teams = array_column($response['overallteamstandings']['teamstandingsentry'], 'team');
switch ($type) {
case 'name':
$key = array_search($team, array_column($teams, 'Name'));
return ($key !== false) ? $teams[$key]['ID'] : false;
break;
case 'city':
$key = array_search($team, array_column($teams, 'City'));
return ($key !== false) ? $teams[$key]['ID'] : false;
break;
default:
return false;
}
}
// get a team's stats based on its ID
function get_stats($response, $team) {
$teams = array_column($response['overallteamstandings']['teamstandingsentry'], 'team');
$key = array_search($team, array_column($teams, 'ID'));
return ($key !== false) ? $response['overallteamstandings']['teamstandingsentry'][$key]['stats'] : false;
}
Example usage (based on your sample data):
echo "ID for city Baltimore is " . get_team_id($response, 'Baltimore', 'city') . "\n";
echo "ID for name Ravens is " . get_team_id($response, 'Ravens', 'name') . "\n";
Output:
ID for city Baltimore is 56
ID for name Ravens is 56
Getting the stats array:
print_r(get_stats($response, 56));
Output:
Array
(
[GamesPlayed] => Array
(
[#abbreviation] => G
[#text] => 14
)
[PassAttempts] => Array
(
[#category] => Passing
[#abbreviation] => Att
[#text] => 384
)
[PassCompletions] => Array
(
[#category] => Passing
[#abbreviation] => Comp
[#text] => 255
)
[PassPct] => Array
(
[#category] => Passing
[#abbreviation] => Pct
[#text] => 66.4
)
[PassGrossYards] => Array
(
[#category] => Passing
[#abbreviation] => Yds
[#text] => 3016
)
)
Demo on 3v4l.org

From php multidimensional array trying to create nested ul li menu (unlimited nested levels)

Here is what i have got http://codepad.org/iDoXXsLX
Have array like this
Array
(
[0] => Array
(
[NumberRenamed] => 17
[TopicName] => Products
[UpperLevelNumberRenamed] => 0
)
[17] => Array
(
[0] => Array
(
[1] => Array
(
[NumberRenamed] => 18
[TopicName] => Computers
[UpperLevelNumberRenamed] => 17
)
)
)
[18] => Array
(
[0] => Array
(
[2] => Array
(
[NumberRenamed] => 16
[TopicName] => Laptops
[UpperLevelNumberRenamed] => 18
)
)
)
[16] => Array
(
[0] => Array
(
[4] => Array
(
[NumberRenamed] => 8
[TopicName] => Dell
[UpperLevelNumberRenamed] => 16
)
)
)
)
Top level item is Products, first sub-level item is Computers, next sub-level is Laptops, then again next sub-level Dell
For each sub-level item UpperLevelNumberRenamed == to closest upper level NumberRenamed.
Want to get result like this
Products
Computers
Laptops
Dell
Acer
Desktops
Home
Tried this
foreach( $main_topics as $k_main_topics => $v_main_topics ){
if( isset($v_main_topics['UpperLevelNumberRenamed']) and $v_main_topics['UpperLevelNumberRenamed'] == 0 ){
//print only top level topics
echo $v_main_topics['TopicName']. '<br/>';
}
else{//if not top level topic
foreach( $v_main_topics[0] as $k_v_main_topics_0 => $v_v_main_topics_0 ){
echo $v_v_main_topics_0['TopicName']. '<br/>';
}//foreach( $v_main_topics[0] as $k_v_main_topics_0 => $v_v_main_topics_0 )
}//else{
}//foreach( $main_topics as $k_main_topics => $v_main_topics )
But get this
Products
Home
Computers
Laptops
Desktops
Dell
Acer
Something incorrect, but can not understand what. Please, advice what need to correct/change in the code
Trying another way
Initial array is one dimensional array. Trying to get ul li navigation from one dimensional.
Here is what i did http://codepad.org/OLtxyL4X
Here's a summary of what it does:
flatten the array recursively
build a multi-dimensional relation map
create 1D relationships that link UpperLevelNumberRenamed to NumberRenamed
print out the multi-dimensional as an ul-li list.
Here it is:
$flat = array();
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($main_topics)) as $i)
$flat[] = $i;
$final = array();
$defs = array();
for ($i = 0; $i < count($flat); $i += 3)
if ($flat[$i + 2] == 0) {
$final[$flat[$i + 1]] = array();
$defs[$flat[$i]] = &$final[$flat[$i + 1]];
} else {
$defs[$flat[$i + 2]][$flat[$i + 1]] = array();
$defs[$flat[$i]] = &$defs[$flat[$i + 2]][$flat[$i + 1]];
}
function array2ul($array) {
$out = "<ul>";
foreach($array as $key => $elem)
$out = is_array($elem) ?
$out . "<li><span>$key</span>" . array2ul($elem) . "</li>" :
$out = $out."<li><span>$key:[$elem]</span></li>";
$out = $out . "</ul>";
return $out;
}
echo array2ul($final);
Output:
<ul><li><span>Products</span><ul><li><span>Computers</span><ul><li><span>Laptops</span><ul><li><span>Dell</span><ul></ul></li><li><span>Acer</span><ul></ul></li></ul></li><li><span>Desktops</span><ul></ul></li></ul></li></ul></li><li><span>Home</span><ul></ul></li></ul>
This shall be a working example using recursion, not tested though:
Define the array
$main_array = Array
(
'10' => Array
(
'name' => 'Products'
'children' => Array
(
'12' => Array
(
'name' => 'Laptop',
'children' => Array
(
'13' => Array
(
'name' => 'Dell',
),
'14' => Array
(
'name' => 'Acer',
)
)
)
'14' => Array
(
'name' => 'Desktop',
'children' => Array
(
'15' => Array
(
'name' => 'Sony',
),
'16' => Array
(
'name' => 'Apple',
)
)
),
)
)
)
Create and call the function :
function createList($main_topics)
{
if($main_topics == null || sizeof($main_topics) <= 0)
{
return '';
}
$list = '<ul>';
foreach($main_topics as $k_main_topics => $v_main_topics )
{
$list .= '<li id="' . $k_main_topics'"> '. $v_main_topics['name'] . ' ' . createList(isset($v_main_topics["children"]) ? $v_main_topics["children"] : null) . '</li>' ;
}
$list .= '</ul>';
return $list;
}
echo createList($main_array);

PHP Multidimensional array into an HTML nested list?

I have an array with data that is nested as per the below (just a simplified example as it has to be "endless" since each family tree can go over X generations):
Array
(
[id] => 121
[name] => Very Important Dogs Bowey Showey
[gen] => 0
[mother] => Array
(
[id] => 128
[name] => Veridique Of Winners
[gen] => 1
[mother] =>
[father] =>
)
[father] => Array
(
[id] => 124
[name] => Rosickys Robocopico
[gen] => 1
[mother] => Array
(
[id] => 75
[name] => Astro Spice
[gen] => 2
[mother] =>
[father] =>
)
[father] => Array
(
[id] => 62
[name] => Your King of the World
[gen] => 2
[mother] =>
[father] =>
)
)
)
And I tried with this PHP function but without success because it indeed goes through each array and creates a bullet point, but I cannot isolate "name" and "ID" as they all come together.
function recurseTree($var){
$out = '<li>';
foreach($var as $v){
if(is_array($v)){
$out .= '<ul>'.recurseTree($v).'</ul>';
}else{
$out .= $v;
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($familytree).'</ul>';
And this is what it gives me:
- 121Very Important Dogs' Bowey Showey0
- 128Veridique Of Winners1
- 124Rosicky's Robocopico1
- 75Astra's Spice2
- 62Lazhar's King of the World2
It gives me an unusable string. Instead, I want to use something like $v['id'] to get the id (and create an a href link) and the name with something like $v['name']... But how?!
The format I am after:
<ul>
<li><span>Mother</a></span>
<ul>
<li><span>Grandmother</span>
<ul>
<li><span>Grand-Grandmother</span></li>
<li><span>Grand-Grandfather</span></li>
</ul>
</li>
<li><span>Grandfather</span>
</ul>
</li>
<li><span>Father</a></span>
<ul>
<li><span>Grandmother</span>
<li><span>Grandfather</span>
</ul>
</li>
</ul>
Here is what you could do:
function recurseTree($var)
{
$out = '<li>';
foreach($var as $k => $v)
{
if(is_array($v))
{
$out .= '<ul>'.recurseTree($v).'</ul>';
}
else
{
switch($k)
{
case 'id':
$out .= 'id='.$v;
break;
case 'name':
$out .= 'name='.$v;
break;
}
}
}
return $out.'</li>';
}
echo '<ul>'.recurseTree($familytree).'</ul>';
Because your array is associative and appears to follow a consistent format, I think you can actually do this without using a loop at all. This should make the formatting much easier.
function recurseTree($var) {
if ($var) {
$link = '<span>'. $var['name']. '</span>';
$parents = '';
if ($var['mother'] || $var['father']) {
$parents = '<ul>'. recurseTree($var['mother']). recurseTree($var['father']). '</ul>';
}
return "<li>$link$parents</li>";
}
}
echo '<ul>' . recurseTree($familytree) . '</ul>';

Searching for specific sub-arrays in a multidimensional array, then loop through the found sub-arrays to get all the values

I need to search the following array for the sub-arrays that start with "prod_", then loop through those sub-arrays to get all the values. The amount of sub-arrays can vary depending on how many products in the cart.
Array
(
[address] => clayton85
[prod_0] => Array
(
[qty] => 2
[style] => American Apparel T-Shirt
[color] => Royal
[size] => Medium
[price] => 33.90
)
[prod_1] => Array
(
[qty] => 1
[style] => Bella Womens T-Shirt
[color] => Teal
[size] => Large
[price] => 17.95
)
[prod_2] => Array
(
[qty] => 1
[style] => Canvas Long Sleeve
[color] => Red
[size] => Large
[price] => 19.95
)
[prod_3] => Array
(
[qty] => 1
[style] => Canvas Long Sleeve
[color] => Red
[size] => Medium
[price] => 19.95
)
[cartTotal] => 91.75
)
I was able to come up with a very messy solution that returns the values by count, but there must be a better, more efficient way. Using PHP 5.5 this is what I came up with.
<?php
$cartArray = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$item_cnt = 0;
foreach ($cartArray as $prod => $option) {
if (strpos($prod, "prod_") === 0) {
echo '<div class="row"><div class="col-xs-12"><div class="co-product">';
$i = 0;
foreach ($cartArray[$prod] as $key => $value) {
if ($i === 0) {echo '<span class="label">' . $value . '</span>'; $item_cnt = $item_cnt + intval($value);}
elseif ($i === 1) {echo '<span class="co-desc">' . $value . '<br>';}
elseif ($i === 2) {echo '<span class="co-subtext"><strong>Color:</strong> ' . $value . ' </span>';}
elseif ($i === 3) {echo '<span class="co-subtext"><strong>Size:</strong> ' . $value . '</span></span>';}
else {echo '<span class="co-price pull-right">$' . $value . '</span>';}
$i++;
}
echo '</div></div></div>';
}
}
?>
Loop through the main array and then just use the keys of the inner array:
foreach ($cartArray as $prod => $option) {
if (strpos($prod, "prod_") === 0) {
echo $option["qty"];
//etc...
}
}

how to iterate through a particular part of an object

I have an object which looks like this
zen_categories_ul_generator Object
(
[root_category_id] => 0
[max_level] => 6
[data] => Array
(
[0] => Array
(
[19] => Array
(
[name] => Brushes
[count] => 0
)
[29] => Array
(
[name] => Clips
[count] => 0
)
[2] => Array
(
[name] => Combs
[count] => 0
)
[27] => Array
(
[name] => Jewellery
[count] => 0
)
)
[1] => Array
(
[57] => Array
(
[name] => Testing
[count] => 0
)
)
And I want to loop through all the information at the level $this->data[0], I'm using
foreach($this->data[0] as $category_id => $category) {
$result .= $category_id.' - '.$category['name'];
}
return $result;
but this will just the last item in the array. so in this case it would only have 27 - Jewellery but none of the other array item would be returned.
What am I doing wrong?
thanks
NB I only need to loop through the data[0] - not data[1] as well!
EDIT - here's a paste bin with a more code to make easier to understand what I'm trying to do and how I'm doing it. Any help gratefully received
http://pastebin.com/Vrw9f7Xh
Question:
Ok, so you want to loop through all the information $this->data[0], to render a menu.
Actually, you were pretty close to the solution, yourself.
The line used for rendering the product items, is:
$result .= ''.$category['name'] . ' (' . $category['count'] . ')';
The following is working example, which works standalone.
You might save it as menu.php and test it.
I had to comment the zen_* function out, but i think the relevant part is the rendering, right?
class zen_categories_ul_generator
{
function setTestData($data) { $this->data = $data; }
function buildMenu() {
$result = '';
// removed home link, unchanged and not important in this example
// submenu
$result .= '<li class="submenu">';
$result .= 'Products';
$count = 0;
foreach($this->data[0] as $category_id => $category) {
$count++;
$result .= '<ul class="level2">';
$result .= '<li class="submenu">';
//$result .= ''.$category['name'].''.$count;
$result .= ''.$category['name'] . ' (' . $category['count'] . ')';
$result .= '</li>';
$result .= '</ul>';
}
$result .= '</li> Items:' . $count;
return $result;
}
}
$object = new zen_categories_ul_generator;
// ok, lets add your example data from outside to the object, in order to test the rendering
$data = array(
0 => array(
19 => array('name' => 'Brushes', 'count' => 5),
29 => array('name' => 'Clips', 'count' => 2),
2 => array('name' => 'Combs', 'count' => 1),
27 => array('name' => 'Jewellery', 'count' => 3)
)
);
$object->setTestData($data);
// render the menu
echo $object->buildMenu();
Result
Count is the number of iterations = the number of Products in a Category.
And the counter behind the product name is from the array, the key "count".

Categories