james Oduro
james Oduro

Reputation: 673

How to separate and assign data in a multi dimensional array via a loop - PHP

I have an associative array of data coming from another script:

while($row  =  mysqli_fetch_assoc($query)){
    $replyArray[] = array(
        'did' => $row['discussion_id'],
        'rid' => $row['reacter_id'],
        'reply' => $row['reply'], 
        'date' => $row['date']
    );  
}

I have a function that will use this array $replyArray:

        //In this function we extract data(discussions) from array
    //This function is called inside disReply function.

    function subDiscussion($replyArray){
                        $reply_count    = count($replyArray);
                        for($x=0; $x < $reply_count; $x++){
                            echo "<br><h3>Data: ".($x +1).' <br>'."</h3>" ;
                            foreach($replyArray[$x] as $key => $value){
                                echo $data= $key.": ". $value."<br>";               

                            }

                        }
                };

The example above returns all associated paired data by just echoing the variable $data.

What I want to achieve is to separate the data(data in paire) into different variables:

$rid = its value

$did = its value

$reply = its value

$date = its value

The reason is because I want to put them in an HTML design in that function later.

Thank you.

Upvotes: 1

Views: 41

Answers (1)

Variable variables will help here:

// inside the final (foreach) loop
foreach($replyArray[$x] as $key => $value){

    $$key = $value;     

}
// now use these variables, $did, $rid, etc., e.g. save to an array or use in a function - else they will be overwritten in next iteration of parent for loop

Read more about variable variables here.

According to what Patrick Q suggested using the PHP extract()

for($x=0; $x < $reply_count; $x++){
    extract($replyArray[$x]);
}

extract() This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable

Upvotes: 2

Related Questions