如何将每个元素存储为 php 中数组的源和目标?

How to store each element as source and destination from array in php?

我有一个包含一些元素的数组,我想要输出,我可以将每个元素存储在 table 中作为源和目标。 例如

    $array = ['1','2','3,'4'];
     
    source | destination |
------------------------------
    1      | 2           |
    1      | 3           |
    1      | 4           |
    2      | 1           |
    2      | 3           |
    2      | 4           |
    3      | 1           |
    3      | 2           |
    3      | 4           |
    4      | 1           |
    4      | 2           |
    4      | 3           |

我想像上面的结构一样存储数据。我尝试了每个循环,但没有得到 this.Please 的完美逻辑帮助我解决这个问题。

使用 foreach 时,您需要遍历数组两次,如果第一个循环中的元素等于第二个循环中的元素,则跳过它,否则将第一个元素添加为源,将第二个元素添加为目标。像这样:

 $array = ['1','2','3','4'];
 
 $newArr = [];
 foreach ($array as $a) {
      foreach ($array as $b) {
          if ($a == $b) {
              continue;
          }
         $newArr[] = [
             'source' => $a,
             'data' => $b,
             ];
    }
 }
 
echo "<pre>";
var_dump($newArr);
echo "</pre>";

结果是:

array(12) {
  [0]=>
  array(2) {
    ["source"]=>
    string(1) "1"
    ["destination"]=>
    string(1) "2"
  }
  [1]=>
  array(2) {
    ["source"]=>
    string(1) "1"
    ["destination"]=>
    string(1) "3"
  }
  [2]=>
  array(2) {
    ["source"]=>
    string(1) "1"
    ["destination"]=>
    string(1) "4"
  }
  [3]=>
  array(2) {
    ["source"]=>
    string(1) "2"
    ["destination"]=>
    string(1) "1"
  }
  [4]=>
  array(2) {
    ["source"]=>
    string(1) "2"
    ["destination"]=>
    string(1) "3"
  }
  [5]=>
  array(2) {
    ["source"]=>
    string(1) "2"
    ["destination"]=>
    string(1) "4"
  }
  [6]=>
  array(2) {
    ["source"]=>
    string(1) "3"
    ["destination"]=>
    string(1) "1"
  }
  [7]=>
  array(2) {
    ["source"]=>
    string(1) "3"
    ["destination"]=>
    string(1) "2"
  }
  [8]=>
  array(2) {
    ["source"]=>
    string(1) "3"
    ["destination"]=>
    string(1) "4"
  }
  [9]=>
  array(2) {
    ["source"]=>
    string(1) "4"
    ["destination"]=>
    string(1) "1"
  }
  [10]=>
  array(2) {
    ["source"]=>
    string(1) "4"
    ["destination"]=>
    string(1) "2"
  }
  [11]=>
  array(2) {
    ["source"]=>
    string(1) "4"
    ["destination"]=>
    string(1) "3"
  }
}

循环中的循环并进行快速检查,这样当索引相同时您就不会打印,这就是您所需要的

$array = [1,2,3,4];

for ($i=0; $i<count($array); $i++){
    for ( $j=0; $j<count($array); $j++){
        if ( $i == $j ) {
            continue;
        }
        echo sprintf("%d - %d\n", $array[$i], $array[$j]);    
    }
}

结果

1 - 2
1 - 3
1 - 4
2 - 1
2 - 3
2 - 4
3 - 1
3 - 2
3 - 4
4 - 1
4 - 2
4 - 3