2009-10-28 64 views
0

我遇到以下问题。我有数字1/2/3/4/5/6,我想将它们分成两组1/3/5和2/4/6。选择必须根据职位进行。这部分工作正常。当我使用implode函数时,我想再次对它们进行分组时会出现问题;它只会看到存储的最后一个数字。我知道它是与我使用这个标志的(我选择了这条路,因为数字来分类的变化量每次):使用implode分组来自while while循环中的信息

$q++; 
$row0 = $row0 + 2; 
$row1 = $row1 + 2; 

,但我找不出办法解决,或另一种方式得到相同的结果。希望有人能在这里指出我的正确方向。我在下面留下了完整的代码。


<? 
$string = "1/2/3/4/5/6"; 
$splitted = explode("/",$string); 
$cnt = count($splitted); 
$q=0; 
$row0=0; 
$row1=1; 
while($cnt > 2*$q) 
{ 
    $p_row = implode(array($splitted[$row0])); 
    echo "$p_row <br>"; 
    $i_row = implode(array($splitted[$row1])); 
    echo "$i_row <br>"; 

    $q++; 
    $row0 = $row0 + 2; 
    $row1 = $row1 + 2; 
} 
$out = "implode(',', $i_row)"; 
var_dump($out); 
?> 

回答

0

您可以分割阵列插入循环索引使用%基团。将每个组放在单独的数组中。这里是例子:

<?php 
    $string = "1/2/3/4/5/6"; 
    $splitted = explode("/",$string); 
    $group_odd = array(); ## all odd elements of $splitted come here 
    $group_even = array(); ## all even elements of $splitted come here 
    for ($index = 0; $index < count($splitted); ++$index) { 
     ## if number is divided by 2 with rest then it's odd 
     ## but we've started calculation from 0, so we need to add 1 
     if (($index+1) % 2) { 
      $group_odd[] = $splitted[$index]; 
     } 
     else { 
      $group_even[] = $splitted[$index]; 
     } 
    } 
    echo implode('/', $group_odd), "<br />"; ## outputs "1/3/5<br />" 
    echo implode('/', $group_even), "<br />"; ## outputs "2/4/6<br />" 
    print_r($group_odd); 
    print_r($group_even); 
?> 
+0

我刚刚检查了您的提示,它很好地工作。一直在努力为我们解决它,并找不到方法。非常感谢:-) – Nigg 2009-10-28 22:58:44

+0

索引计算可能非常复杂 – 2009-10-28 23:01:28

0

根据他们的位置?那么,基于它们在数组中索引的均匀性/奇异性进行拆分?

这样的事情?

<?php 

$string = "1/2/3/4/5/6"; 

list($evenKeys, $oddKeys) = array_split_custom(explode('/', $string)); 

echo '<pre>'; 
print_r($evenKeys); 
print_r($oddKeys); 

function array_split_custom(array $input) 
{ 
    $evens = array(); 
    $odds = array(); 
    foreach ($input as $index => $value) 
    { 
    if ($index & 1) 
    { 
     $odds[] = $value; 
    } else { 
     $evens[] = $value; 
    } 
    } 
    return array($evens, $odds); 
} 
1

我错过了它似乎的问题。相反,我给这个优化。

$string = "1/2/3/4/5/6"; 
$splitted = explode("/", $string); 
$group = array(); 
for ($index = 0, $t = count($splitted); $index < $t; ++$index) { 
    $group[$index & 1][] = $splitted[$index]; 
} 
$oddIndex = $group[0]; //start with index 1 
$evenIndex = $group[1]; //start with index 2 

echo "odd index: " 
    . implode('/', $oddIndex) 
    . "\neven index: " 
    . implode('/', $evenIndex) 
    . "\n"; 
+1

我能想到的唯一的事情就是他希望在数组索引上做它,而不是数组值。 – Zak 2009-10-28 23:15:06