所以我在表单中有一个多维数组(实际数组可以有500多个成员)
$marr = array( array("s_id" => 1, 1.25 , 15),
array("s_id" => 2, 0.75 , 25),
array("s_id" => 1, 1.15 , 7)
);
我试图将其分解为由成员数组的s_id值分组/索引的数组
$sarr = array(
1 => array(
array("s_id" => 1, 1.25 , 15),
array("s_id" => 1, 1.15 , 7)
),
2 => array(
array("s_id" => 2, 0.75 , 25)
)
);
在php中是否有内置函数来执行此操作或执行此操作的最佳实践方法?
答案 0 :(得分:4)
没有内置功能可以提供此结果。相反,您需要迭代数组,并检查匹配s_id
值的键是否已存在。如果它没有在该密钥上创建新数组。
$marr = array( array("s_id" => 1, 1.25 , 15),
array("s_id" => 2, 0.75 , 25),
array("s_id" => 1, 1.15 , 7)
);
// Holds the whole output
$output = array();
// Looping over the original array
foreach ($marr as $subarr) {
// Check if the output array already has the s_id as a key
if (!isset($output[$subarr['s_id']])) {
// Initialize it
$output[$subarr['s_id']] = array();
}
// Then append the current sub-array to the s_id array key
$output[$subarr['s_id']][] = $subarr;
}
// Then call ksort() on the output array
// to sort the s_id keys in ascending order
ksort($output);
http://codepad.viper-7.com/SSBrAl
Array
(
[1] => Array
(
[0] => Array
(
[s_id] => 1
[0] => 1.25
[1] => 15
)
[1] => Array
(
[s_id] => 1
[0] => 1.15
[1] => 7
)
)
[2] => Array
(
[0] => Array
(
[s_id] => 2
[0] => 0.75
[1] => 25
)
)
)