簡體   English   中英

PHP循環兩個數組,如果索引是最后一個倒帶數組

[英]PHP Loop two arrays if index of one is last rewind array

我有兩個數組。 第一個數組是名稱,它有5個名稱。 第二個數組是組,它有3組。 我想遍歷兩個數組並將每個索引名稱設置為索引組。 如果組索引完成,我想重新啟動第二個數組。

我嘗試將組索引重置為0,如果它到達最后一項,但它不起作用。

$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to the: " .$groups[$index]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

當它到達第四個名稱項時,組項應該是1.有沒有辦法做這樣的思考?

預期結果

John - 1

Jane - 2

George - 3

Jim - 1

Jack - 2

先感謝您

我們假設數組是數字索引的(從0開始),並且沒有跳過的索引(即$group數組總是被定義為range(1, $n); )。

然后,您可以將模數運算符%與該數組的長度一起使用,如下所示。

foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to group " .$groups[$index % count($groups)]. ".\n";
   echo $result;
}

您可以對組索引進行模數%模數。

$groups[$index % sizeOf($groups)]

<?php
$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {
   $result = "The student: " . $name . " belongs to the: " .$groups[$index%sizeOf($groups)]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

結果: https//3v4l.org/LnOHAK

The student: John belongs to the: 1group<br><br>The student: Jane belongs to the: 2group<br><br>The student: George belongs to the: 3group<br><br>The student: Jim belo

嘗試這個! 在此代碼中,如果添加新組,則沒有問題。

<?php

$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

$groups = [
  '1',
  '2',
  '3'
];

foreach ($names as $index => $name) {

   $result = "The student: " . $name . " belongs to the: " .$groups[$index % count($groups)]. "group" ;
   echo ($result);
   echo "<br>";
   echo "<br>";
}

這適用於任何類型的數組

$names = [
  'John',
  'Jane',
  'George',
  'Jim',
  'Jack'
];

global $groups;

$groups = [
  '1',
  '2',
  '3'
];

$newArr = array_combine(
            $names, 
              array_merge(
                  $groups,
                  array_map(
                    function($v){
                      global $groups;
                      return $groups[$v%count($groups)]; 
                    }, 
                   array_keys(array_diff_key($names, $groups))
                 )
              )
          );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM