Array get 2nd item - php

foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if (something) {
echo "cat.: ".$item->{'category'}. "<br>";}
If i have 2x "category" to choose, how to set it to get the second one, not the 1st in the row?

The simplest way would be to use a counter variable:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ != 1)
echo "cat.: ".$item->{'category'}. "<br>";
However, this will include every category after the first. If you only want the second category, you could use the same approach:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ == 2)
echo "cat.: ".$item->{'category'}. "<br>";

This gives you the second category and also ensures that you'll get the first category when there's no second one:
foreach ($xml->xpath('programme[#channel="1"]') as $item) {
if (something) {
if (isset($item->category[1]) && !empty($item->category[1])) {
echo 'cat.: '.$item->category[1].'<br />';
} else {
echo 'cat.: '.$item->category[0].'<br />';
}
}
}

Related

Filtering an array with foreach and for loop

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'];
}
}

Foreach last item with condition

foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
// if last NOT CANCELLED item:
echo '<strong>ITEM....</strong><br />';
} else {
// ignored completely
}
}
I need to add <strong> arround the last item which did not get cancelled... I know how to check the last item of an array or iterator, but with the condition in the if case, how'd you do this?
Will I need 2 loops?
Update & Solution: I solved this by reversing the logic and to find the first item rather than the last.
I'll keep the question up if someone wants to comment or answer anyways.
try this:
$i=0;
$counter=0;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
$counter=$i;
}
$i++;
}
$i=0;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
if( $counter==$i){
echo "<strong>".$item."</strong></br>"
}
}
$i++;
}
what about this?
$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
$lastNonCancelledItem = $item;
} else {
// ignored completely
}
}
echo '<strong>' $lastNonCancelledItem; //profit
If display these items is a complex task that you do not wish to repeat in 2 places make some sort of function to display the item
$lastNonCancelledItem = null;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
$view->showItem($item);
$lastNonCancelledItem = $item;
} else {
// ignored completely
}
}
echo $view->showItem($lastNonCancelledItem, TYPE_STRONG); //profit (or whatever)
Can you try this,
$coun = count($orderItems);
$i=1;
foreach ($orderItems as $item) {
if ($item->isNotCancelled()) {
echo 'ITEM....<br />';
// if last NOT CANCELLED item:
}else {
// ignored completely
}
if($i==($coun-1))
echo '<strong>ITEM....</strong><br />';
$i++;
}

generate unique ID for on foreach loop?

Current I use toggle to show/hide details. I need to give each div a unique ID in foreach loop. I'm not sure how to make it works on an echo string. Can you help me?
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++count;
}
}
?>
I need to make $count in 2 position on the code is same. I got error with this code.
Thank you
Updated:
Actually the code is not just as I give here. I tried with your code but doesnt work.
You can view full at http://www.codesend.com/view/7d58acb2b1c51149440984ec6568183d/ (pasw:123123)
You've writen ++count instead of ++$count
It seems you're not using $i.
You're initializing $count on every loop.
This is supposed to work:
<?php
$i = 0; /* Seems redundant */
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++; /* Seems redundant */
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/><a href="#" class="show_info"
id="dtls'.$count.'">Show Details</a>
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>
++count is wrong, it should be ++$count;
try this
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>
first:
remove this or put it outside of the foreach loop :
$count = 0;
second:
don't use only number for id and use it with a character or word like this :
id = "element'.$count.'"
Third :
what is $i ?
if it's useless remove it!
Forth
change ++count to ++$count
CODE :
<?php
$i = 0;
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>

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

How to manipulate first 3 entries in array

I am currently working on a project where i am pulling out data using
while($r = mysql_fetch_array($the_data))
i want to make the first, say 3-4 results a different background color and then leave the rest as already styled, i am sure there is some simple option here but i just don't know where to look really...
Hope you can help, thanks !
Are you looking for something like:
#specialResult {background-color: #fff; }
#normalResult {background-color: #000; }
So when you are looping through your while statement, you will want to keep track of what result number you are on:
$i = 0;
while (...)
{
if ($i < 4) echo "<div class='specialResult'>";
else echo "<div class='normalResult'>";
.... rest of your code
$i++;
}
for shorter looking code you could do:
$i = 0;
while (...)
{
?><div class='<?php echo ($i++ < 4 ?"specialResult":"normalResult); ?>'><?php
.... rest of your code
}
<?php
$i = 0;
$r = mysql_fetch_array($the_data);
foreach($r as $row) {
if($i <= 4) {
// Do special styling...
} else {
// Do normal styling.
}
$i++;
}
?>
Or did I misunderstand?
You can also try something like :
$i = 0;
while ( ( $row = mysql_fetch_assoc ( $result ) ) && $i < 4 ) {
/* Your first 4 rows */
echo 'Special : ' . $row['title'];
++$i; // Don't forget to increment
} while ( $row = mysql_fetch_assoc () ) {
/* Normal way */
echo $row['title'] . ' is already outdated';
}
And prefer mysql_fetch_assoc() instead of mysql_fetch_array() ;)

Categories