How to manipulate first 3 entries in array - php

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() ;)

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 howto sizeof(JSON:array[])

I have a bug in my code but the solution is buried deep in a JSON return
https://api.instagram.com/v1/users/self/media/liked?access_token=207436640.c57b856.b0a8944d1e0c4e70a6ec581679c656b5
There are array[17] I must loop through
foreach ($arr['data'][0]['likes']['data'] as $liker){
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
Works fine for one, but
for($i = 0; $i < sizeof($arr['data'][]); $i++){
echo '<img src="'.$arr['likes']['data']['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
has less than desirable results.
Fatal error: Cannot use [] for reading in /var/www/localhost/htdocs/instagram2.php on line 68
or if I remove the [], I get 'undefined 'likes'.
How do I properly loop through a JSON subarray?
You way of approaching the for compared to the foreach is wrong. In the foreach the current item during the iteration is automatically assigned to $liker, however nothing like this occurs in the for. You are only incrementing the value of $i.
/// #shaddy has said, this is the correct way to access the array size
/// it is more optimal to calculate it outside of the loop.
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// and then access each of the subitems inside $item
...
}
But you also have other problems. You are seemingly trying to output the image of each of the profile_pictures for the likers; but this is also an array of data. In your first example you are directly stepping through this array, so everything works. In your second however you are only looping the container array, and not the list of likers. To get this to work you must have a second loop:
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// best to check for existence before accessing to avoid errors
if ( !empty($item['likes']['data']) ) {
$likers = $item['likes']['data'];
$len2 = sizeof($likers);
/// step each of the likers
for($k = 0; $k < $len2; $k++){
$liker = $likers[$k];
if ( !empty($liker['profile_picture']) ) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
}
/// the username field is also part of the user array inside item
if ( !empty($liker['username']) ) {
echo '<p> '.$liker['username'].'</p></br>';
}
}
}
}
However the above all looks quite complicated, I usually don't use for loops in php, foreach has a much nicer interface to work with, and is designed to work with arrays:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item['likes']['data']) ) {
foreach ( $item['likes']['data'] as $k => $liker ) {
if ( !empty($liker['profile_picture']) ) {
echo '<img src="' . $liker['profile_picture'] . '" /></br>';
}
if ( !empty($liker['username']) ) {
echo '<p> ' . $liker['username'] . '</p></br>';
}
}
}
}
Of course you may just have been wanting to loop through the likers array just like in your first example, to do that with a for you just need:
$likers = $arr['data'][0]['likes']['data'];
$len = sizeof($likers);
for( $i = 0; $i < $len; $i++ ){
echo '<img src="' . $likers[$i]['profile_picture'] . '" /></br>';
echo '<p> ' $likers[$i]['username'] . '</p></br>';
}
please note:
There is also another caveat to be aware of, and this will cause some of the above snippets to fail if it is not true. All the above code is always working with arrays, and so the $arr array must only contain arrays. However your dataset shows a mixture of arrays and objects. When dealing with objects in PHP you need to use a different accessor.
As I am unable to see how you are loading your JSON it is difficult to advise, as depending on the manner objects can be converted into arrays. All your examples have been treating every part of your structure as an array, and that is why I have assumed the same in the above.
However the standard way would be to use json_decode which would/should preserve the array/object difference by default. This means where ever there is an object you will need to use $obj -> prop rather than $obj['prop'], so my preferred example above would look like this:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item->likes['data']) ) {
foreach ( $item->likes['data'] as $k => $liker ) {
if ( !empty($liker->profile_picture) ) {
echo '<img src="' . $liker->profile_picture . '" /></br>';
}
if ( !empty($liker->username) ) {
echo '<p> ' . $liker->username . '</p></br>';
}
}
}
}
Also if you prefer working just with arrays, you could use something like this:
https://coderwall.com/p/8mmicq/php-convert-mixed-array-objects-recursively
Well $arr['data'][] is invalid way to reference the data value of the array the correct one is $arr['data']
for($i = 0; $i < sizeof($arr['data']); $i++){
foreach ($arr['data'][$i]['likes']['data'] as $liker) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
}
You can read more about arrays here http://php.net/manual/en/language.types.array.php .

Array get 2nd item

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

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

PHP <BR> After 2 loops

I wanted to add <br> after every 2 loops.
The loop will run 8 times and after every 2 loops I want to add <br>
Can anyone help?
The loop will look like this:
while($row = mysql_fetch_array( $result2 )) {
}
Notice: this isn't a pretty good syntax. If you want to achive some style with TD rows you could use new css selector: http://reference.sitepoint.com/css/pseudoclass-nthchild
$i=0;
for(;;) {
$i++;
if ($i%2==0)
echo '<br>';
}
$c=0;
while($row = mysql_fetch_array( $result2 )) {
//PUSH YOUR CODE
$c++;
if($c%2==0)
echo "<br/>";
}
Inside your loop:
$i = 0;
while(whatever){
if($i % 2 == 0){
echo '<br/>';
}
$i++;
}

Categories