PHP Group array by values

2019-03-06 02:10发布

问题:

I have an array like this:

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 
)

And I want to group the values into an array like this:

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
          )
)

There may be many other items named like that: ing_NUMBER_type

How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:

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

What is wrong? Can you advice?

回答1:

It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:

$result = array();

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

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


回答2:

<?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;
}
?>

This creates:

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
        )

)


回答3:

What I'd do is something like this:

$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;
}

Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.

EDIT. If you know you'll always have the numbers start from 1, you can replace $number = $matches[1]; for $number = $matches[1] - 1;, this way you'll get exactly the same result you posted as your example.