我有一个数组,有点像:
Array (
[1] => Array
(
[1] => 21
[2] => 3
[0] => Analyst
)
[2] => Array
(
[1] => 47
[2] => 8
[0] => Catalysis
)
[3] => Array
(
[1] => 1
[2] => 0
[0] => Biomaterials
)
[4] => Array
(
[3] => 12
[4] => 2
[0] => Analyst
)
[5] => Array
(
[5] => 12
[6] => 2
[0] => Analyst
)
...
然而,我想用相同的[0]值重新编号这些条目,这样我就可以使用了
[1] => Array
(
[1] => 21
[2] => 3
[3] => 12
[4] => 2
[5] => 12
[6] => 2
[0] => Analyst
)
到目前为止,我已经尝试将[0]值从$results
数组中取出,方法是将它们放在自己的数组中,并说如果您已经在那里了,那么将[3]和[4]添加到新数组中[1]和[2]的位置,但这不起作用。
$final = array();
$jArray = array();
foreach($results as $key => $result) {
if(!in_array($result[0],$jArray) && !empty($result[0])) {
$jArray[$i] = $result[0];
$i++;
}
}
for($x = 0; $x < count($results); $x++) {
$k = array_search($results[$x][0],$jArray);
if(!isset($results[$x][1]))
$final[$k][1] = $results[$x][1];
if(!isset($results[$x][2]))
$final[$k][2] = $results[$x][2];
if(!isset($results[$x][3]))
$final[$k][3] = $results[$x][3];
if(!isset($results[$x][4]))
$final[$k][4] = $results[$x][4];
if(!isset($results[$x][5]))
$final[$k][5] = $results[$x][5];
if(!isset($results[$x][6]))
$final[$k][6] = $results[$x][6];
}
有什么更简单的方法吗?
您可以这样做。。。
$new_arr=array();
$arkeys = array_unique(array_map(function ($v){ return $v[0];},$arr));
foreach($arr as $k=>$arr1)
{
$new_arr[$arr1[0]][]=array_slice($arr1,0,count($arr1)-1);
}
foreach($arkeys as $v)
{
$new_arr[$v] = call_user_func_array('array_merge', $new_arr[$v]);
}
print_r($new_arr);
OUTPUT :
Array
(
[Analyst] => Array
(
[0] => 21
[1] => 3
[2] => 12
[3] => 2
[4] => 12
[5] => 2
)
[Catalysis] => Array
(
[0] => 47
[1] => 8
)
[Biomaterials] => Array
(
[0] => 1
[1] => 0
)
)
工作演示
如果只想按子数组的第一个元素分组,一个循环就足够了:
$result = array();
foreach ($array as $sub_arr) {
$key = $sub_arr[0];
unset($sub_arr[0]);
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] += $sub_arr;
}
此处为
$final = array();
foreach($results as $key => $result) {
if (!in_array($result[0], array_keys( $final ) ) && !empty($result[0])) {
$final[$result[0]] = array( $result[0] );
}
foreach($result as $k => $v) {
if ($k != 0 && isset($v)) {
$final[$result[0]][$k] = $v;
}
}
}