I made a post regarding a code for Adobe Analytics API. I am using a code to retrieve the first and second element (dimension) which is called 'breakdown'. The number varies depending on the data we have for this element.
I am using a loop with i=10 but I want to take everything. Which is the best way to achieve that?
I am using this code:
foreach ($json->report->data as $element)
{
// putting an excessive number for i
for ($i=0;$i<100;$i++)
{
// checking if the object exists
if (isset($element->breakdown[0]->breakdown[$i]->name))
{
echo $element->breakdown[0]->breakdown[$i]->name;
// putting the data in a list I created before
array_push($list, array(''.$element->year.'-'.$element->month.'-'.$element->day, $element->breakdown[0]->name, $element->breakdown[0]->breakdown[$i]->name, $element->breakdown[0]->breakdown[$i]->counts[0], $element->breakdown[0]->breakdown[$i]->counts[1]));
}
else
{
// Break the loop. All the objects are in the row. So, if there is not any for i=45 then there won't be any for i>45
continue;
}
}
}
where I am trying to get all the objects. I am checking if the objects exist. If they don't, I want this loop to stop (second loop).
Use break instead of continue to exit a loop
break stops the current loop continue goes to the next iteration of the loop.
To get out of both loops use break 2;
You can break the loop with break.
for more information: http://php.net/manual/en/control-structures.break.php
foreach ($json->report->data as $element)
{
// putting an excessive number for i
for ($i=0;$i<100;$i++)
{
// checking if the object exists
if (isset($element->breakdown[0]->breakdown[$i]->name))
{
echo $element->breakdown[0]->breakdown[$i]->name;
// putting the data in a list I created before
array_push($list, array(''.$element->year.'-'.$element->month.'-'.$element->day, $element->breakdown[0]->name, $element->breakdown[0]->breakdown[$i]->name, $element->breakdown[0]->breakdown[$i]->counts[0], $element->breakdown[0]->breakdown[$i]->counts[1]));
}
else
{
// Break the loop.
break;
}
}
}
Related
I'm working on in_array() method. If the value read is already in the array it should be skipped and proceed to the next value. If the current value is not on the array yet, it should be pushed to the array.
here's my code:
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$Res_Array = array();
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Problem: It seems that it ignores my condition which is if(in_array($SQL_Result_Time, $Res_Array, true)){break; } and still inserts the value into the array. It still duplicates data
Question:
How to prevent the duplication data where if the current value was found inside the array it would just skip the statement and proceed to another value for checking the array and so on?
Is my logic on checking the value on the array is right?
You are re-initialising your array on every iteration of the while loop. You should declare it outside of the loop:
$Res_Array = array();
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
$SQL_Result_Time = $Result_Data_2['Interpretation_Time'];
/* Some statements here */
if(in_array($SQL_Result_Time, $Res_Array, true)){
break;
}
else{
array_push($Res_Array, $Number, $SQL_Questionnaire_ID, $SQL_User_ID, $SQL_Psychology_FirstName, $SQL_Psychology_LastName, $SQL_Result_Date, $SQL_Result_Time);
}
echo "<pre>";print_r($Res_Array);echo "</pre>";
}
Also, as mentioned by Marvin Fischer in his answer, your break statement will terminate the while loop on the first duplicated value. You should instead use continue
while ($Result_Data_2 = mysqli_fetch_array($Result)){ //130 rows from database
...
if(in_array($SQL_Result_Time, $Res_Array, true)){
continue;
}
....
}
This question should clarify any issues you have with break and continue statements
First of all, inside of a loop you should use continue, otherwise you cancel the whole loop, secondly you empty $Res_Array at the beginning of every loop purging the old data, inserting the new one and echoing it again
I'm having a few issues with foreach loops in PHP.
I have an outer foreach loop and an inner foreach loop.
The basics of the loops are, I have some posted data from a form, and some data from a db. The outer loop, loops through each post data and then compares this with data from the database inner loop.
The issue I have is, upon each outer loop, if an entry is found on the inner loop, how does the outer loop know its been found and then not repeat the entry.
So, here's the code I am using, i've commented so you can see the problem im having with the logic
// get posted data
foreach($posted_vals as $post_key => $post_value) {
// query all data in assignments table
foreach($existing_ids as $db_key => $db_value) {
// check if user_id($db_value) matches ($post_value),
// if not then post to db
// if this loop does not find matching data and
// posts to the database, how does the outer loop
// know its been found and then not post again to database
}
// any entries not found in db, post to db ... er but hang on,
// how do i know if any entries were posted???
}
you can set a flag variable isFound whether the post were found in inner loop or not. Initially the variable is false but if the post is found in inner loop it will be updated to true then in outer loop you can check if the isFound is true or fale. Thus you can check whether your post was found or not in inner loop. Here is how you can do it:
// get posted data
foreach($posted_vals as $post_key => $post_value) {
$isFound = false;
// query all data in assignments table
foreach($existing_ids as $db_key => $db_value) {
//if found in db then set $isFound = true;
}
//if(!isFound) that means if the post was not found
// any entries not found in db, post to db ... er but hang on,
// how do i know if any entries were posted???
}
It might become more clear when you put the db-comparison in a separate function:
foreach($posted_vals as $post_key => $post_value) {
if(compareWithDbValues($post_value)) {
return true;
}
}
function compareWithDbValues($post_value) {
foreach($existing_ids as $db_key => $db_value) {
if($db_value == §post_value) {
return true;
}
}
return false;
}
If you do not have it in a separate function just use break instead of return true in the inner for loop.
Im trying to NOT show a specific field inside the loop, so I need to get a list of all the field types so I can use it inside the if statement. Not sure how I can do this properly?
foreach($this->sections as $k => $section){
foreach($section['fields'] as $k => $type){
//This makes a nice list of all the stuff I need
echo '<li>'.var_dump ($type['type']).'</li>';
}
//Outside the loop doesn't dump all of the contents just some
echo '<li>'.var_dump ($type['type']).'</li>';
if($type['type'] != 'switch'){
//My stuff
}
}
The idea is to loop all the field types, except for one specific type declared in the if statement. The for each is so I can get a list of all the field types.
As you might already experienced the construct you propose is not desired since the if statement will be executed after the loop has already ended.
You can use the continue keyword to jump to the next iteration and skip fields you're not interested in.
foreach ($section['fields'] as $k => $type) {
if ($type['type'] != 'switch') {
continue;
}
// do stuff
}
http://php.net/manual/en/control-structures.continue.php
foreach ($bing_array as $bing_array_val)
{
foreach ($final_array as $final_array_val)
{
if ($final_array_val["link"] == $bing_array_val["link"])
{
$final_array_val["rank"] += $bing_array_val["rank"];
}
}
}
The above code has two foreach loops, which are nested.
It should test every bing_array["link"] against every final_array["link"] and if they are the same, the final_array["rank"] value should be += bing_array["rank"] but when I echo final_array, the ["rank"] values are unchanged.
I assume this is a syntax problem, where am I going wrong?
Thanks
You need to use the reference syntax (& prefix):
foreach ($final_array as &$final_array_val)
{
}
unset($final_array_val);
Note that the unset is required to break the reference to the last value. Read more here.
Here is the actual code you need :
foreach ($bing_array as &$bing_array_val)
{
foreach ($final_array as &$final_array_val)
{
if ($final_array_val["link"] == $bing_array_val["link"])
{
$final_array_val["rank"] += $bing_array_val["rank"];
}
}
unset(&$final_array_val);
}
unset(&$bing_array_val);
In your initial code, each time you were looping on $final_array, it was creating a temporary value called $final_array_val containing the content. Then, you modified it, and then it was replaced for each occurence of the foreach.
By passing the variables by reference, instead of creating a new temporary variable in the foreach, you use the actual variable which will keep the modifications you have done to it.
I have the following code:
$friendsOrdered= new SplPriorityQueue();
... // Code to fill up the priority queue
print_r($friendsOrdered);
$i = 0;
foreach($friendsOrdered as $f) {
}
echo "<br><br>";
print_r($friendsOrdered);
When I look at the output of the prints I can see that after the loop the priority queue is empty. Is there a way of stopping the foreach from removing elements?
Thanks!
You cannot stop the loop from dequeuing elements, as that is the nature of the data structure. You could, however, create a copy of the object before the loop so your data isn't lost:
$friendsOrdered_copy = clone $friendsOrdered;
foreach($friendsOrdered_copy as $f) {
// ...
}