PHP组数组的值

时间:2012-01-19 16:18:28

标签: php multidimensional-array grouping

我有一个这样的数组:

Array ( 
     [0] => ing_1_ing 
     [1] => ing_1_amount 
     [2] => ing_1_det 
     [3] => ing_1_meas
     [4] => ing_2_ing 
     [5] => ing_2_amount 
     [6] => ing_2_det 
     [7] => ing_2_meas 
)

我想将值分组为这样的数组:

Array (
   [0] => Array(
             [0] => ing_1_ing
             [1] => ing_1_amount
             [2] => ing_1_det
             [3] => ing_1_meas
          )
   [1] => Array(
             [0] => ing_2_ing
             [1] => ing_2_amount
             [2] => ing_2_det
             [3] => ing_2_meas
          )
)

可能还有许多其他名称如下:ing_NUMBER_type

如何按照我想要的方式将第一个数组分组?我试过了,但出于某种原因,strpos()有时会失败:

$i = 1;     
foreach ($firstArray as $t) {
            if (strpos($t, (string)$i)) {
                $secondArray[--$i][] = $t;
            } else {
                $i++;
            }
        }

有什么问题?你能建议吗?

3 个答案:

答案 0 :(得分:4)

这取决于您要实现的目标,如果您想通过块使用array_chunk方法拆分数组,并且如果您尝试根据数字创建多维数组,则可以在您的方法中使用sscanf方法循环解析值:

$result = array();

foreach ($firstArray as $value)
{
    $n = sscanf($value, 'ing_%d_%s', $id, $string);

    if ($n > 1)
    {
        $result[$id][] = $value;
    }
}

答案 1 :(得分:1)

<?php
$ary1 = array("ing_1_ing","ing_1_amount","ing_1_det","ing_1_meas","ing_2_ing","ing_2_amount","ing_2_det","ing_2_meas");
foreach($ary1 as $val)
{
    $parts = explode("_",$val);
    $ary2[$parts[1]][]=$val;
}
?>

这会创建:

Array
(
    [1] => Array
        (
            [0] => ing_1_ing
            [1] => ing_1_amount
            [2] => ing_1_det
            [3] => ing_1_meas
        )

    [2] => Array
        (
            [0] => ing_2_ing
            [1] => ing_2_amount
            [2] => ing_2_det
            [3] => ing_2_meas
        )

)

答案 2 :(得分:0)

我要做的是这样的事情:

$result = array();
foreach ($firstArray as $value)
{
  preg_match('/^ing_(\d+)_/', $value, $matches);
  $number = $matches[1];
  if (!array_key_exists($number, $result))
    $result[$number] = array();
  $result[$number][] = $value;
}

基本上你遍历你的第一个数组,看看那里有多少个数字,并把它放在最后一个数组中的正确位置。

修改即可。如果您知道自己始终从1开始编号,则可以将$number = $matches[1];替换为$number = $matches[1] - 1;,这样您就可以得到与您的示例完全相同的结果。< / p>