Php 我想将重复的tag_name数组分组到一个数组下
从以下数组:Php 我想将重复的tag_name数组分组到一个数组下,php,arrays,Php,Arrays,从以下数组: Array ( [0] => Array ( [tag_name] => Quant-Arithmetic [student_marks] => 1.05 [total_marks] => 2.00 [student_count] => 1 [level] => Easy [ove
Array
(
[0] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.05
[total_marks] => 2.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 52
)
[1] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.10
[total_marks] => 4.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 28
)
[2] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 0.20
[total_marks] => 1.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 20
)
[3] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.00
[total_marks] => 6.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 17
)
[4] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.50
[total_marks] => 6.00
[student_count] => 1
[level] => Hard
[overall_percentage] => 25
)
)
类似的事情:因为我需要一个基于标记名的数组,它的所有级别都在该数组中,这样我就可以得到单个标记名及其级别和百分比,以便进一步计算
[tag_name]
{
[level]:[overall_percentage]
[level]:[overall_percentage]
.
.
}
.
.
.
这将添加并创建一个$newArray,如下所示:
Array(
'tag_name' => Array(
'Medium' => '27'
)
)
试试这个代码
$array =array
(
'0' => array
(
'tag_name' => 'Quant-Arithmetic',
'student_marks' => ' 1.05',
'total_marks' => ' 2.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 52',
),
'1' => array
(
'tag_name' => ' Quant-Arithmetic',
'student_marks' => ' 1.10',
'total_marks' => ' 4.00',
'student_count' => ' 1',
'level' => ' Medium',
'overall_percentage' => ' 28',
),
'2' => array
(
'tag_name' => ' Quant-Algebra',
'student_marks' => ' 0.20',
'total_marks' => ' 1.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 20',
)
);
// declare a new array
$new_array = array();
foreach($array as $values){
// trim array elements
$trimmed_array=array_map('trim',$values);
if(isset($new_array[$trimmed_array['tag_name']])){
//add elements to array
$new_array[$trimmed_array['tag_name']][$trimmed_array['level']] = $trimmed_array['overall_percentage'];
}else{
// create new array
$new_array[$trimmed_array['tag_name']] = array($trimmed_array['level'] => $trimmed_array['overall_percentage']);
}
}
// php array
print_r($new_array);
// json
echo json_encode($new_array);
输出:数组
Array
(
[Quant-Arithmetic] => Array
(
[Easy] => 52
[Medium] => 28
)
[Quant-Algebra] => Array
(
[Easy] => 20
)
)
输出:Json
{"Quant-Arithmetic":{"Easy":"52","Medium":"28"},"Quant-Algebra":{"Easy":"20"}}
你试过什么吗?你想要什么?JSON还是数组?JSON和数组都在这里:你确定这是OP想要的吗?我认为你的循环是完美的,但不是输出。我已经编辑了我的响应。我的原始版本包含了一个额外的数组级别深度,因为我觉得会有多个级别具有相同的键值(例如2x Easy)
{"Quant-Arithmetic":{"Easy":"52","Medium":"28"},"Quant-Algebra":{"Easy":"20"}}