I want to dynamically fill key and value in an associative array using for loop in PHP

$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";

$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';

}   
//trim the , from last value
$str = rtrim($str, ",");

$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");

Here i added "value1"=>"$row->field1","value2"=>"$row->field2","value3"=>"$row->field3","value4"=>"$row->field4" using $str Dynamically with the help of for loop because it is dynamic not fixed.

I want to make this array like the below so it can process or work - It's my desired output

array("data"=>array("userid"=>"$row->uid","value1"=>"$row->field1","value2"=>"$row->field2","value3"=>"$row->field3","value4"=>"$row->field4","acc_id"=>"$acc_id","tloop"=>"$timeloopc"),"next"=>"$next");

Output is -
when i print this the it shows output like this - Here array taking the value of $str as string and

Array ( [data] => Array ( [user1] => 1 [0] => "value1"=>"$row->field1","value2"=>"$row->field2","value3"=>"$row->field3","value4"=>"$row->field4","value5"=>"$row->field5" [user2] => 2 [fi] => 3 ) [next] => 4 )

It's now processing the $str values as sting "value1"=>"$row->field1"...4

Help me to dynamically fill key and value in an associative array using for loop

When i am making array dynamic it's not working like array. If i make it static it works fine.

So please help me to make $str value from string to array value(object)...

Here is complete code -

<?php 
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";

$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';

}   
//trim the , from last value
$str = rtrim($str, ",");

$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>

`

Sorry, your code and explanation are very long and confusing. It's late and I'm having a hard time understanding what you're asking for. That's probably why you haven't gotten any respones yet.

However, I'm REALLY good at PHP. Maybe if you could very briefly (in not more than a sentence or so) explain what you need help with (if you still need help, that is), and I'll do my best to help you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.