我有一个多维数组(实际数组可以有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中做到这一点或一些最佳实践的方式做到这一点?
没有内置函数可以提供此结果。相反,您需要遍历数组,并检查与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
)
)
)