0

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

$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 循环并将电子邮件发送给不同的公司。任何指针将不胜感激!

4

1 回答 1

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_valueshttp ://us3.php.net/array_values

于 2013-11-06T03:55:51.937 回答