B
B
Beeshop872021-06-14 17:45:46
PHP
Beeshop87, 2021-06-14 17:45:46

Explain why such strange behavior of foreach() and in_array() in PHP?

Greetings! I'm a rookie in the ranks of backenders. Faced with an incomprehensible phenomenon for me when working with arrays.
1. There is an array of basket items. Each product has its own pickup store ID.
2. There is also an array of store IDs from which pickup is possible.
It is necessary to check whether all goods have the possibility of self-delivery, and if so, find out which store(s) of the available ones (second array) to arrange self-delivery.

here is an array of products and store IDs where it is available:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(2) "28"
    [1]=>
    string(2) "29"
  }
  [1]=>
  array(2) {
    [0]=>
    string(2) "28"
    [1]=>
    string(2) "29"
  }
  [2]=>
  array(1) {
    [0]=>
    string(2) "29"
  }
}


Here is an array with pickup points:

array(2) {
  [0]=>
  string(2) "28"
  [1]=>
  string(2) "29"
}


My code works for some reason))

// если в массиве товаров нет магазинов, то пустая строка

        foreach( $productAr as $product ) {

            if (!isset($product["STORES"]) ){
                $inStores[] = '';
            } else {

                $inStores[] = $product["STORES"];

            }
        }

        // есть ли у товаров магазины

        if( !empty($inStores) ) {
            $i = 0;
            $s = 0;
            foreach ($inStores as $item) {
                if (empty($item[$i])) {
                    break;
                }

                // какой магазин из доступных к самовывозу имеется у всех товаров

                $s++;  // тут вся суть вопроса! если итерацию делаю как положено, после поиска в массиве, то в результате в  $arPickupID получаю все ID, с которыми идёт сравнение. А в этом варианте возвращает единственно общий

                if (in_array($storesAvailable[$s], $item)) {
                    $arPickupID[] = $storesAvailable[$s];
                }
                $i++;
            }
        }


I couldn't find answers on google. Curious as to why it works this way.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gian_tiaga, 2021-06-14
@Beeshop87

Your code is completely unreadable.
You are using foreach incorrectly in principle
. Here is an example pseudo-code, see how simple it is. Perhaps you need to drive algorithms, read about standard functions, the database seems to suffer greatly.

foreach ($products as $product) {
     if (!empty(array_intersect($product['stores'], $allowStores))) {
          $product['allow'] = true;
     }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question