我正在使用PHP,并且有一个看起来像这样的数组数组:


Array
(
    [0] => Array
        (
            [gr_number] => 1
            [batch] => A
            [maths] => 80/100
            [english] => 80/100
            [science] => 80/100
            [hindi] => 80/100
            [computer] => 80/100
            [socialscience] => 85/100
        )
    [1] => Array
        (
            [gr_number] => 2
            [batch] => A
            [maths] => 80/100
            [english] => 80/100
            [science] => 80/100
            [hindi] => 80/100
            [computer] => 80/100
            [socialscience] => 86/100
        )
    [2] => Array
        (
            [gr_number] => 3
            [batch] => A
            [maths] => 80/100
            [english] => 80/100
            [science] => 80/100
            [hindi] => 80/100
            [computer] => 80/100
            [socialscience] => 87/100
        )
)

如您所见,主数组中有一些 suject 元素,o 我想将所有主题元素合并到同一个数组中,像这样

Array
(
    [0] => Array
        (
            [gr_number] => 1
            [batch] => A
            [result_details] => maths : 80/100,english:80/100,science:80/100,hindi:80/100,computer:80/100,socialscience:85/100;
        )
    [1] => Array
        (
            [gr_number] => 2
            [batch] => A
            [result_details] => maths : 80/100,english:80/100,science:80/100,hindi:80/100,computer:80/100,socialscience:85/100;  
      )
    [2] => Array
        (
            [gr_number] => 3
            [batch] => A
            [result_details] => maths : 80/100,english:80/100,science:80/100,hindi:80/100,computer:80/100,socialscience:85/100;  
        )
)

您可以简单地在 foreach 循环中添加一个新元素result_details,其中包含来自其他元素的组合值,并取消设置以后不需要的值:

foreach($arr as &$val){
    $val['result_details']='maths:'.$val['maths'].',english:'.$val['english'].',science:'.$val['science'].',hindi:'.$val['hindi'].',computer:'.$val['computer'].',socialscience:'.$val['socialscience'];
    unset($val['maths'],$val['english'],$val['science'],$val['science'],$val['hindi'],$val['computer'],$val['socialscience']);
}

演示

您可以将array_maparray_diff_keyarray_intersect_key结合使用。不知何故像这样:

$keys = array('gr_number', 'batch');
$excludes = array_combine($keys, array_fill(0, count($keys), 0));
$result = array_map(
    function ($arr) use($excludes) {
        $ret = array_intersect_key($arr, $excludes);
        $arr = array_diff_key($arr, $excludes);
        $ret['result_details'] = implode(', ', array_map(
            function ($v1, $v2) { return "$v1:$v2"; },
            array_keys($arr), array_values($arr)
        ));
        return $ret;
    },
    $array
);

演示

相关内容

  • 没有找到相关文章

最新更新