考虑这段代码:
$results = array();
foreach(array('Bob' => 24, 'Joe' => 17, 'Jimmy' => 38, 'Joe' => 10, 'Bob' => 5, 'Sam' => 8) as $key => $val){
$results[$key][] = $val;
}
echo '<pre>';
print_r($results);
echo '</pre>';
输出:
Array
(
[Bob] => Array
(
[0] => 5
)
[Joe] => Array
(
[0] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
PHP 忽略重复键,当您从数据库中检索数据时,您必须创建 $results 数组,假设您这样做:
while () {
$col1 = $row["col1"];
$col2 = $row["col2"];
$results[$col1][] = $row["col2"];
}
现在结果数组必须是这样的:
Array
(
[Bob] => Array
(
[0] => 24
[1] => 5
)
[Joe] => Array
(
[0] => 17
[1] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
现在,很容易像这样搜索 colmun1 名称:
$values_for_colmn1 = $results[$column1]; //which is an array
// 对数组乘积使用 array_product() 函数
$product_for_column1 = array_product($values_for_colmn1);