php foreach loop with continue if value has already been echoed - php

I have a foreach loop and I need to add a continue if the value has already been echoed. I can't find the right syntax. The loop:
foreach ($results as $result) {
echo $result->date . "<br />";
}
But I need to add in a continue so that if the value has already been echoed, and it comes up again in the loop it gets skipped. I can't quite get the if/continue statement quite right.
Thoughts, suggestions, ideas?

As mentioned by #JonathanKuhn in the comments - here is how you would run that loop:
$already_echoed = array();
foreach ($results as $result) {
if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
echo $result->date . "<br />";
}
$already_echoed[] = $result->date; //store all dates in an array to check against.
}

$echoedArray = array();
foreach ($results as $result) {
if (isset($echoedArray[$result->date])) {
continue;
}
echo $result->date . "<br />";
$echoedArray[$result->date] = true;
}

$alreadyOutput = array();
foreach ($results as $result) {
if(in_array($result->date, $alreadyOutput)){
continue;
}
$alreadyOutput[] = $result->date;
echo $result->date . "<br />";
}

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

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

trying to get multiple nested values from jagged json array using json_decode

I'm trying to print the url and filename of the files array inside each instance that is shown. Each for instance
http://xbins.nyc/mvscu
mvscu.zip
http://xbins.nyc/mvsc
mvsc.zip
http://xbins.nyc/mvscjp
mvscjp.zip
The above is how the output should be once the code below runs. it throws errors since it's checking the whole code for the further nested arrays.
{
"accountId":"Ja4Rulez",
"finished":"true",
"createdAt":"2016-05-20",
"releaseDate":"1998",
"updatedAt":"2016-05-20",
"expires":"1468905126822",
"requestTableUS":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvscu",
"filename":"mvscu.zip"
}
]
}
},
"requestTableMain":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvsc",
"filename":"mvsc.zip"
}
]
}
},
"requestTableJp":{
"tableCAPCOM":{
"tableName":"CAPCOM",
"partial":"true",
"files":[
{
"url":"http://xbins.nyc/mvscjp",
"filename":"mvscjp.zip"
}
]
}
}
}
The above query is sent to the $data variable below and then json_decoded into $obj.
<?php
$obj = json_decode($data, TRUE);
foreach($obj as $row){
foreach($row as $k){
foreach($k as $j){
foreach($j as $l){
echo $l['url'];
echo "<br />";
echo $l['filename'];
echo "<br />";
}
}
}
}
?>
Also the number of returned "requestTable"s returned vary but here it's simply 3, but it can change from 3 to 100+. I need to make sure the loop can accommodate additional "requestTables" if available.
Most of the elements of $obj are not arrays, so you can't use foreach on them. You only want to drill down into the elements whose keys begin with requestTable, and then you only want to loop through the files, not everything in that element.
foreach ($obj as $key => $row) {
if (substr($key, 0, 12) == 'requestTable')) {
foreach ($row['tableCAPCOM']['files'] as $l) {
echo $l['url'];
echo "<br />";
echo $l['filename'];
echo "<br />";
}
}
}
This snippet should do exactly what you want.
<?php
$array = json_decode($json, true);
foreach($array as $key=>$data) {
if (strpos($key, 'requestTable') !== false) {
foreach($data['tableCAPCOM']['files'] as $file) {
echo $file['url'];
echo "<br />";
echo $file['filename'];
echo "<br />";
}
}
}
?>

Multiple nested array from MySQL query

I'm using foreach loops to access records in a nested array:
while ($row = mysql_fetch_assoc($result)){
$test_groups[$row['group_name']][] = $row['lab_test'];
}
foreach($test_groups as $group_name => $tests){
echo "<tr><td><span class='test_group_name'>" . $group_name . "</span></td></tr>";
foreach($tests as $test){
echo "<tr><td>" . $test . "</td></tr>";
}
echo "<tr><td> </td></tr>";
}
echo '</table>';
This works OK. Now I need to add another level to the nested array, like:
$departments[$row['department_name']][$row['group_name']][] = $row['lab_test'];
Would this work and how should I adjust the for each loops above to cater for this?
Assign to array should be with [] at the end
$departments[$row['department_name']][$row['group_name']][] = $row['lab_test'];
Foreach loop will be:
foreach ($departments as $dep_name => $groups) {
echo $dep_name;
foreach ($groups as $group_name => $tests) {
echo $group_name;
foreach ($tests as $test) {
echo $test;
}
}
}
It's just with echoes, make there HTML as you need.

output specific array key for each result

i have a search engine for my page. as a result i would like to ouput the array key for each result.
so i have this code:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
if (!empty($errors){
foreach ($results as $result){
echo "this is result: "
.$result['key']; //thought would be the solution, its not.
}
} else {
foreach ($errors as $error){
$error;
}
}
i also tried using a counter like:
$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
$counter = 0;
if (!empty($errors){
foreach ($results as $result){
$counter++;
echo "this is result: "
.$counter;
}
} else {
foreach ($errors as $error){
$error;
}
}
what doesnt work as i thought and is still not that professional.
so if there is someone who could tell me how to solve this i really would appreciate. thanks a lot.
foreach ($results as $key => $result) {
echo 'this is result: ' . $key;
}
The current key will be assigned to $key and the value for that property will be assigned to $result
http://php.net/manual/en/control-structures.foreach.php
edit
In response to your comments, I think this is what you're trying to achieve:-
$i=0;
foreach($results as $result) {
echo 'this is result: ' . ++$i;
}
foreach($arr as $key=>$val){
//do something with key and value
}
Here in code you can check first if $results array is not empty because sometime due to empty $results array foreach generates error
/*Check if $results array is empty or not*/
if(!empty($results)){
foreach ($results as $key=>$result){
/*result you want to show here according conditions*/
}
}

Categories