james Oduro james Oduro - 5 months ago 14
PHP Question

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.


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.