按ID拆分数组然后处理拆分数组

时间:2013-11-06 03:49:16

标签: php arrays php-5.3 oscommerce

我正在尝试组织一组我从数据库中提取的数组。以下是该数组的示例:

$productsarray = Array ( 
  [0] => Array ( [id] => 789 [pro_name] => Product1 [dsid] => 5 ) 
  [1] => Array ( [id] => 237 [pro_name] => Product2 [dsid] => 3 ) 
  [2] => Array ( [id] => 665 [pro_name] => Product3 [dsid] => 7 ) 
  [3] => Array ( [id] => 164 [pro_name] => Product4 [dsid] => 3 ) 
)

我正在尝试根据[dsid]对这些数组进行分组,如下所示:

$productsarray[0] = Array ( 
  [0] => Array ( [id] => 237 [pro_name] => Product2 [dsid] => 3 ) 
  [1] => Array ( [id] => 164 [pro_name] => Product4 [dsid] => 3 ) 
)

$productsarray[1] = Array ( 
  [0] => Array ( [id] => 789 [pro_name] => Product1 [dsid] => 5 ) 
)

$productsarray[2] = Array ( 
  [0] => Array ( [id] => 665 [pro_name] => Product3 [dsid] => 7 ) 
)

我需要将它们分组,这样我就可以通过$ productsarray []运行一个while循环,然后将电子邮件发送给不同的公司。任何指针都将非常感谢!

1 个答案:

答案 0 :(得分:1)

使用$dsid作为第一级数组键创建一个新数组,将所有后续值添加到其中,然后使用array_values重置数组键:

<?php

$products = array();

foreach($productsarray as $current) {

    $dsid = $current['dsid'];
    $products[$dsid][] = $current; // use $dsid as common array key for now

}

// reset array keys
$productsarray = array_values($products);

?>

有关array_values的更多信息:http://us3.php.net/array_values