Add new values to foreach loop from inside the loop [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
Is possible to add new values to the array that the foreach is working with? So it will run (n+x) where n is the number of elements of the array before the foreach starts and x is the number of elements that were added to the array.
Yes, I tested.. and looks like NO.. so I'd like to know if I can do something to this work.
foreach($pages_to_visit as $key => $source){
global $products;
$links = baixarSource($source);
foreach($links as $link){
global $products;
global $pages_to_visit;
if(preg_match("/somestore\.com/i", $link)){
if(!in_array($link, $pages_to_visit)){
$pages_to_visit[] = $link;
}else if(preg_match("/\/produto\//i", $link) && !in_array($link, $products)){
$products[] = $link;
echo $link."\n";
}
}
}
unset($pages_to_visit[$key]);
sleep(0.2);
}

As you already figured out, using foreach() it is not possible, however when you use for() the task becomes quite easy:
for ($i=0; $i<count($array); $i++) {
//code
}
This is due to count($array) being (re)calculated before every iteration. You can also use a variable that you increment yourself (incrementing is a way easier task than counting an array)
$max = count($array);
for ($i=0; $i<$max; $i++) {
//code
//when push an element just do $max++;
}
Of course this will only work with numerical indices but that seems to be the case here.

You need to specify the "runner" variable as a reference in the foreach code if you want to modify the array itself from within the foreach.
http://us2.php.net/manual/en/control-structures.foreach.php
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Example (will only count to 9):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as $blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}
Example2 (this time it will count to 10 using the additional element added from inside the foreach):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as &$blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}

Not sure if I get your question right... I think what you try to do doesn't make much sense at all any way.
echo $countBefore = count($data);
foreach ($data $as $value) {
$data[] = 'Some new value';
}
echo $countAfter = count($data);

Related

How to sort an array with name, date and quantity? PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this array and I would like to sort the dates for the graphs.[]
1
Before I was using this function because I was only bringing in the array example ````$data[$date] = $total``` but now I am bringing in the name, date and total.
foreach ($_data_ as $key => $value) {
$_date[] = $value->fecha;
$_dataOpportunities[$value->name][$value->fecha] = $value->total;
}
foreach ($_dataOpportunities as $key => $value) {
for ($i=0; $i < count($_date) ; $i++) {
if (!array_key_exists($_date[$i],$value)) {
$_dataOpportunities[$key][$_date[$i]] = 0;
}
}
}
//Order by date //Not order
foreach ($_dataOpportunities as $key => $value) {
//dd($value);
uksort($value,['self','compare_date_keys']);
}
dd($_dataOpportunities);
public static function compare_date_keys($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
The dd($value) returns this:
And when it exits the foreach and returns the variable dd($_dataOpportunities); it returns me the following:
Dates are still not sorted.
I tried uksort and usort and still the date order does not work.
Assuming the multi-dimensional array is $array:
function key_cmp_date($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
foreach($array as $key=>$val){
uksort($array[$key],"key_cmp_date");
}
I haven't tested it, but this should suffice.
Try using ksort($arr) function to sort the array. I haven't tried this, but I think this will work.

Laravel Helper to merge Period arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Laravel Version:7.0
I would like to know how to create this helper.
Input is date range array. For example:
$input1 = [2020-07-19, 2020-07-25];
$input2 = [2020-07-26, 2020-08-01];
$input3 = [2020-08-01, 2020-08-07];
$input4 = [2020-10-01, 2020-10-07];
$input5 = [2020-10-19, 2020-10-25];
I would like to make one helper function.
function mergeDate($array)
{
...
}
So when I use this helper, I would like to get as following result.
$array = [$input1, $input2, $input3, $input4, $input5];
$mergedResult = mergeDate($array);
$mergedResult[0] = [2020-07-19, 2020-08-07];
$mergedResult[1] = [2020-10-01, 2020-10-07];
$mergedResult[2] = [2020-10-19, 2020-10-25];
Can anyone help me how to make mergeDate function?
Input period elements aren't overlapped.
Thank you!
This would be my first guess at how to solve it.
public function merge($array){
$results = [];
foreach ($array as $element){
if (sizeof($results) == 0){
array_push($results,$element);
}else{
$found = null;
foreach ($results as $key => $r){
if (Carbon::parse($element[0])->equalTo(Carbon::parse($r[1])))
{
$found = $key;
break;
}
}
if (!is_null($found)){
$results[$found][1] = $element[1];
}else{
array_push($results, $element);
}
}
}
return $results;
}
It is a simple take on the problem. If our resulting array is empty we add the first element otherwise we iterate over the results to find a matching pair of the elements end date and the start date of the item in the results array. If we find a matching start end pair we replace the results end value with the elements end value. Otherwise we have no overlap and we can add it as a new item to the results array.
An interesting library to use would be the Spatie/Period library.
https://github.com/spatie/period
#edit
since the array is not sorted as mentioned in a comment above, you would have to sort it prior.

PHP Array multiple keys [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Heres what I want to do:
<?php
$array = array("array1" => array(), "array2" => array());
function mdparser(){
for($i = 0;$i < func_num_args();$i++){
//foreach arguement go 1 child deeper
return $array["array1"] //if second argument exists ["array2"];
?>
I need this to parse multidimensional arrays independantly , so I can use it on any Multi dimensional array.
Still just guessing at what you're trying to achieve
$this->myArray = array("key1" => array("key2" => array(1,2,3)));
protected function mdparser(){
$result = $this->myArray;
for($i = 0;$i < func_num_args();$i++){
$result = $result[func_get_arg($i)];
}
return $result;
}
$result = this->mdparser('key1', 'key2', 1);
PHP >= 5.6 allows variadics to simplify this:
protected function mdparser(...$args){
$result = $this->myArray;
foreach($args as $arg){
$result = $result[$arg];
}
return $result;
}
Just pass the array to the method when you call it, assuming you are calling it from somewhere where $array is in scope
Also change the array you are building so you have a known, easily processible index i.e. 0.1.2... and not 'array1', 'array2',....
<?php
$array = array( array(), array() );
function mdparser($array){
return $array[count($array)-1];
}
$last_array = mdparser($array);
?>
This should return the last array within the outer array.
Doesnt matter now ive found a way thanks anyways:
function search_array(){
$args = func_get_args();
$arg_num = func_num_args();
for($i = 0;$i < $arg_num;$i++){
$arg = $args[$i];
//foreach arguement go 1 child deeper
$array = $this->array[$arg];
$this->array = $array;
//if second argument exists ["array2"];
}
}

Why does $k reset itself back to zero every time through the loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why does $k reset itself back to zero every time through the loop?
$fruit = array ( “orange”, “apple”, “grape” );
$testvar = “no”;
while ( $testvar != “yes” ) {
$k = 0;
if ($fruit[$k] == “apple” ) {
$testvar = “yes”;
echo “apple\n”;
} else {
echo “$fruit[$k] is not an apple\n”;
}
$k++;
}
The problem is that you are creating a new variable each time the while loop runs. If you put $k before the while loop, then you will be able to increment it and get an accurate view of how many times the while loop has executed.
Note PHP only has function scope, so $k will still be available after this loop ends.
You are initializing the variable $k inside the while loop.
while ( $testvar != “yes” ) {
$k = 0;
This will reset its value each time until the while condition fails. Initialize $k before while loop so that it's value is initialized only once, like
$k = 0;
while ( $testvar != “yes” ) {

Check if an array contains another array with PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an array contains all elements of another array
I have posted something like this to the Stackoverflow before, but the answers do not fully satisfy me. That's why I'm posting the question again, but changing the question all along.
Some people helped me to construct a function that checks if an array($GroupOfEight[$i]) that is an element of a multidimensional array($GroupOfEight) equals another array($stackArray), disregarding the number ordering in the arrays.
However, what I need to check is whether the mentioned array($stackArray) contains any another array($GroupOfEight[$i]) in the multidimensional array($GroupOfEight) or not, that means main array($stackArray) can consist more elements than subarrays($GroupOfEight[$i]).
Here is the one working code that I've gathered so far, but need to be modified to the version I want:
<?php
$GroupOfEight = array (
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10)
);
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
/*$stackArray gets value with POST Method by URL parameter.
This is just the example. As you see this array contains
$GroupOfEight[4], and also it contains many other numbers.*/
/* The function given below checks if $stackArray equals any
of the subarrays of $GroupOfEight. However, we want to check
if $stackArray caontains any of the subarrays of function.
If it does, function should return the index number, if it
doesnt it should return -1.*/
function searcheight($stackArray,$GroupOfEight){
for($i=0; $i<count($GroupOfEight);$i++){
$containsSearch = (count(array_intersect($stackArray,$GroupOfEight[$i])) == count($stackArray) && count(array_intersect($stackArray,$GroupOfEight[$i])) == count($GroupOfEight[$i]));
if($containsSearch){
return $i; //This specifies which index in GroupOfEight contains a matching array
}
}
return -1;
}
// Calling the function that is given above.
echo searcheight($stackArray,$GroupOfEight);
?>
Any logical ideas or solutions will kindly be much appreciated. Thanks.
This one is fast:
function contains_array($array){
foreach($array as $value){
if(is_array($value)) {
return true;
}
}
return false;
}
You can try
$GroupOfEight = array(
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10));
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
function searcheight($stackArray, $GroupOfEight) {
$list = array();
for($i = 0; $i < count($GroupOfEight); $i ++) {
$intercept = array_intersect($GroupOfEight[$i], $stackArray);
$len = count($intercept);
if ($len % 4 == 0) {
$list[$i] = $len;
}
}
arsort($list);
if (empty($list))
return - 1;
return key($list);
}
echo searcheight($stackArray, $GroupOfEight);
Output
5

Categories