douzhuo8871 2016-11-29 06:08
浏览 274
已采纳

将数组的第一个索引值作为键,将第二个索引值作为新数组的值

For below code:

 $data = $student_internal_mark->$internalmark_col;
        $d = explode("|",$data);
        foreach ($d as $value) {
              $register_no_arr = explode(":",$value);
              $marks = explode(',',$register_no_arr[1]);
              print_r($register_no_arr);
        }

I got output as below:

Array
        (
            [0] => SD00000001
            [1] => 9.8,3,2,3,4
        )
        Array
        (
            [0] => SD00000002
            [1] => 6.8,2.4,34,34,34
        )
        Array
        (
            [0] => SD00000003
            [1] => 4.6,2.4,23,23,23
        )
        Array
        (
            [0] => SD00000004
            [1] => 6.4,1.2,32,32,32
        )

I want to retrieve the values in such a way that i will get (output) an array as:

student_marks[SD00000001]=9.8,3,2,3,4
student_marks[SD00000002]=6.8,2.4,34,34,34
student_marks[SD00000003]=4.6,2.4,23,23,23
.......
student_marks[SD0000000N]=................

So that I can display marks in each array, as given below

Register No | Mark 1 | Mark 2 |Mark 3 | Total

S5001 | 3 | 2 | 3 | 8

S5002 |4 | 4 |6 | 14

S5003 |1 |3 |5 | 9

  • 写回答

5条回答 默认 最新

  • dqusbxh44823 2016-11-29 06:18
    关注

    Just use foreach. Try this:

    $arr = array(
      array("SD00000001", "9.8,3,2,3,4"),
      array("SD00000002", "6.8,2.4,34,34,34"),
      array("SD00000003", "4.6,2.4,23,23,23"),
      array("SD00000004", "6.4,1.2,32,32,32"),
    );
    
    $student_marks = array();
    foreach($arr as $values) {
        $student_marks[$values[0]] = $values[1];
    }
    
    echo '<pre>';
        print_r($student_marks);
    echo '</pre>';
    

    UPDATE

    This is your given:

    $data = 'SD00000001:9.8,3,2,3,4|SD00000002:6.8,2.4,34,34,34|SD000000‌​03:4.6,2.4,23,23,2‌​3|‌​SD00000004:6.4,1.2,3‌​2,32,32'; 
    $student_marks = array();
    $d = explode("|",$data);
    foreach($d as $values) {
        $valuesArr = explode(":", $values);
        $student_marks[$valuesArr[0]] = $valuesArr[1];
    }
    
    echo '<pre>';
    print_r($student_marks); 
    echo '</pre>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?