Dayz
Dayz

Reputation: 269

Get arrays in different variables in PHP

When I execute below code:

print_r($marks);

Output is:

Array ( [Dane] => 1 [Mary] => 6 [Jon] => 2) Array ( [Dane] => 3 [Mary] => 2 [Jon] => 1) Array ( [Dane] => 2 [Mary] => 7 [Jon] => 1)

Suppose if many subjects are there (here in example 2 are there). How to get a output as given below ?. I want to store marks in each subject in different variables.

Desired output:

$subject1=Array ( [Dane] => 1 [Mary] => 6 [Jon] => 2) 
$subject2=Array ( [Dane] => 2 [Mary] => 7 [Jon] => 1)
.
.
.
$subjectn=Array ( [Dane] => 1 [Mary] => 8 [Jon] => 2)

Upvotes: 0

Views: 54

Answers (1)

Goku
Goku

Reputation: 241

you can loop your array and create new arrays:

$marks = array(
    array( 'Dane' => 1, 'Mary' => 6, 'Jon' => 2),
    array( 'Dane' => 3, 'Mary' => 2, 'Jon' => 1),
    array( 'Dane' => 2, 'Mary' => 7, 'Jon' => 1)
);

foreach($marks as  $mark_index => $mark){
    ${"subject" . $mark_index} = $mark;     
}

and the result will be new arrays $subject1, $subject2, $subject3 with values of each array.

Upvotes: 1

Related Questions