为每个连接两个索引值

时间:2012-10-18 12:25:25

标签: php arrays

我有这样的循环

$rr=array();

foreach($relations as $key=>$type){
  $rr[$relationType->U2U_Related_USR_ID]=$type[$k]->MSTT_Name.' / '.$type[$k+1]->MSTT_Name;
  $k++;
}

我只得到第一个指数值。如何为每个索引值连接两个索引值。

2 个答案:

答案 0 :(得分:0)

增加 2

$rr = array();

for ($i = 0, $n = count($type); $i < $n; $i += 2) {
    $t1 = $type[$i];
    $t2 = $type[$i + 1];
    $rr[$relationType->U2U_Related_USR_ID] = $t1->MSTT_Name.' / '.$t2->MSTT_Name;
}

注意: $type的长度应为偶数!

答案 1 :(得分:0)

你可以在你的循环中使用2对夫妇键/值:

foreach($relations as $key=>$type){

    list( $odd_key, $odd_value ) = each( $relations );

    //... your code here

    // This work with a step by 2 elements. If you need step by 1,
    // add the following line at the end of the loop :

    //prev( $relations )
}