Dayana Benny Dayana Benny - 3 days ago 5
PHP Question

Make first index's value of array as a key and second index's value as value of new array

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

Answer

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>';
Comments