我如何对数组值吗? [英] How do I make pairs of array values?

查看:119
本文介绍了我如何对数组值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下数组作为输入:

  $输入=阵列('A','B','C','D');
 

我在寻找一种方法,使循环虽然这阵,写下每一个可能对两个值。在这个例子中:AB AC AD BC BD光盘。请注意,BA不能算作一对,因为AB已经提到的:

  $输出=阵列(
  'A'=> B,
  'A'=> 'C',
  'A'=> 'D',
  'B'=> 'C',
  'B'=> D
);
 

这是如何得到这个启动的任何输入AP preciated!

解决方案

  $输出=阵列();
为($ i = 0; $ I<的sizeof($输入); $ I ++){
  $ K ​​= $输入[$ i];
  为($ J = $ I + 1; $ J<的sizeof($输入); $ J ++){
    $ V = $输入[$ J]。
    $输出[] =阵列($ K => $ V);
  }
}
 

修改

由于您的评论中,重组后的输出

  $输出=阵列();
//见下文
为($ i = 0; $ I<的sizeof($输入); $ I ++){
  $ K ​​= $输入[$ i];
  $ V =阵列();
  为($ J = $ I + 1; $ J<的sizeof($输入); $ J ++){
    $ V [] = $输入[$ J]。
  }
  $输出[] =阵列($ K => $ V);
}
 

这将会给你'D'作为最后一行=>阵列(),如果你不想HTI您必须更改

 为($ i = 0; $ I<的sizeof($输入); $ I ++){
 

 为($ i = 0; $ I<的sizeof($输入)-1; $ I ++){
 

Consider the following array as input:

$input = array('A', 'B', 'C', 'D');

I'm looking for a way to make loop though this array, writing down every possible pair of two values. In this example: AB AC AD BC BD CD. Please not that BA doesn't count as a pair, since AB is already mentioned:

$output = array(
  'A' => 'B',
  'A' => 'C',
  'A' => 'D',
  'B' => 'C',
  'B' => 'D'
);

Any input on how to get this started is appreciated!

解决方案

$output=array();
for ($i=0;$i<sizeof($input);$i++) {
  $k=$input[$i];
  for ($j=$i+1;$j<sizeof($input);$j++) {
    $v=$input[$j];
    $output[]=array($k=>$v);
  }
}

Edit

As of your comment, the restructured output

$output=array();
//See below
for ($i=0;$i<sizeof($input);$i++) {
  $k=$input[$i];
  $v=array();
  for ($j=$i+1;$j<sizeof($input);$j++) {
    $v[]=$input[$j];
  }
  $output[]=array($k=>$v);
}

This will give you 'D'=>Array() as a last row, if you don't want hti you have to change

for ($i=0;$i<sizeof($input);$i++) {

to

for ($i=0;$i<sizeof($input)-1;$i++) {

这篇关于我如何对数组值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆