按值拆分php数组

时间:2012-02-22 19:59:50

标签: php arrays

我有这个数组

array
  0 => 
    array

      'prodid' => string '2' (length=1)
      'qty' => int 2
      'price' => string '100.00' (length=6)
      'sid' => string '13' (length=2)
  2 => 
    array

      'prodid' => string '3' (length=1)
      'qty' => int 1
      'price' => string '380.00' (length=6)
      'sid' => string '13' (length=2)
  1 => 
    array

      'prodid' => string '8' (length=1)
      'qty' => int 1
      'price' => string '300.00' (length=6)
      'sid' => string '24' (length=2)

如何将其拆分为多维数组,其值'sid'匹配如此。

array
  0 => 
    array

      0 => 
        array
          'prodid' => string '2' (length=1)
          'qty' => int 2
          'price' => string '100.00' (length=6)
          'sid' => string '13' (length=2)
      1 => 
        array
          'prodid' => string '2' (length=1)
          'qty' => int 2
          'price' => string '100.00' (length=6)
          'sid' => string '13' (length=2)

  1 => 
    array

      0 => 
        array
          'prodid' => string '7' (length=1)
          'qty' => int 1
          'price' => string '200.00' (length=6)
          'sid' => string '15' (length=2)

3 个答案:

答案 0 :(得分:2)

您选择要分组的值作为新阵列的键并将成员推送到该

$new = array();
foreach($array as $member)
{
    $key = $member['group-value'];
    $new[$key][] = $member;
}

然后使用array_values

从新数组中提取裸值
$new = array_values($new);

就是这样。如果你想省略最后一部分,你也可以自己创建密钥的映射和它的数字索引:

$new = array();
$keys = array();
foreach($array as $member)
{
    $key = $member['group-value'];
    isset($keys[$key]) || $keys[$key] = count($keys);        
    $new[$keys[$key]][] = $member;
}

答案 1 :(得分:2)

对于PHP5.3 +

$result = array_reduce (
  $array,
  function ($item, $result) {
    if (!isset($result[$item['sid']])) $result[$item['sid']] = array();
    $result[$item['sid']][] = $item;
    return $result;
  },
  array()
)

答案 2 :(得分:1)

// $ouput array will be indexed by the 'sid' value
$output = array();

// Iterate over the main array and create a new subarray if 
// it doesn't already exist, or add to it if it does.
foreach($input as $subarr) {
  if (!isset($output[$subarr['sid']]) {
    // New array indexed by sid
    $output[$subarr['sid']] = array();
  }
  // Append the whole array
  $output[$subarr['sid']][] = $subarr;
}

注意:这会产生与您描述的略有不同的输出,因为它使用sid作为数组键而不是仅从0开始索引:

array
  // Note key difference...
  // sid == 13
  13 => 
    array
      0 => 
        array
          'prodid' => string '2' (length=1)
          'qty' => int 2
          'price' => string '100.00' (length=6)
          'sid' => string '13' (length=2)
      1 => 
        array
          'prodid' => string '2' (length=1)
          'qty' => int 2
          'price' => string '100.00' (length=6)
          'sid' => string '13' (length=2)
  // sid == 15
  15 => 
    array

      0 => 
        array
          'prodid' => string '7' (length=1)
          'qty' => int 1
          'price' => string '200.00' (length=6)
          'sid' => string '15' (length=2)