Using PHP Foreach with 3 Arrays - php

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) {
}
}

Related

Multiple json in one foreach

Hey i have five json from all getting information now i encountered with problem like this -> from five different json i need to get latest videoId who newer shows first and all it need put to one function foreach for my too hard i try it do about 5hours and stay in same step
Json 1 json 2
All code need from this two json get latest(newest) videoId in one foreach echo
<?php
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'));
$i = 0;
foreach($videoList1->items as $item){
if(isset($item->id->videoId)) {
echo $item->id->videoId;
if ( ++$i > 3) {
break;
}
}
}
Tray this:
$videoList1 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCKLObxxmmAN4bBXdRtdqEJA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList2 = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCynfZM0Edr9cA4pDymb2rEA&maxResults=50&key=AIzaSyDVTF2abNVa5pRitb8MVz1ceJFhE-2y_qk'),true);
$videoList = array_merge($videoList1["items"],$videoList2["items"]);
/// sort lastet first
foreach ($videoList as $key => $part) {
$sort[$key] = strtotime($part['snippet']['publishedAt']);
}
array_multisort($sort, SORT_DESC, $videoList);
foreach ($videoList as $video) {
if(isset($video["id"]["videoId"])) {
echo 'publishedAt: '. $video['snippet']['publishedAt'] . ' VideoID: ' . $video["id"]["videoId"] . "\n </br>";
}
}

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.

How to show all XML Attribute values thru PHP Foreach

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

Restarting a PHP Loop

I have this piece of code
foreach($mnthArrPtrn as $m => $mn)
{
if(!isset($catName)) {
$catVals = array();
$prevCat = $catName = $pntChrtQry[0]['CAT']['categoryname'];
$pntVals .= '{name:'.$catName.',data:[';
}else if($prevCat != $catName) {
$prevCat = $catName;
$catVals = array();
$pntVals .= '{name:'.$catName.',data:[';
}
foreach($pntChrtQry as $key => $val){
$catName = $val['CAT']['categoryname'];
if($prevCat != $catName){
continue 2;
}
echo '<br />$m::'.$m;
echo '<br />$mn::'.$mn;
echo '<br />$val::'.$val[0]['MNTH'];
if($m == $val[0]['MNTH'] || $mn == $val[0]['MNTH']){
$catVals[] = $val[0]['total'];
}
}
pr($catVals);
if(!isset($catName)){
$pntVals .= ']},';
}
$catName = $val['CAT']['categoryname'];
}
1st loop iterates over a months array which are joined as a key value pair.
What I am doing here is on getting a new catName I continue the internal loop but at the same time I want to restart loop 1 with $prevCat,$catName still preserving their values.
Is this possible? Sorry If this is a silly question.
I tried converting the first one to a while statement and use a reset then but It didn't help me.
Something like this will allow you to arbitrarily restart a loop:
while (list($key, $value) = each($mnthArrPtrn)) {
if ($needToRestart) {
reset($mnthArrPtrn);
}
}
See more here.

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