paranoid paranoid - 6 months ago 8
PHP Question

Merge two array with index in php

I have code like this

foreach($tests as $test){
if($test=='true') {
$temp[]['name']='a';
$temp[]['child']='b';
}
else{
$temp[]['name']='c';
$temp[]['child']='d';
}
}
prtint_r($temp);


Result is :


[{"name":"c"},{"child":"d"},{"name":"c"},{"child":"d"},{"name":"a"},{"child":"b"},{"name":"c"},{"child":"d"}]


But I want this result :


[[{"name":"c"},{"child":"d"}],[{"name":"c"},{"child":"d"}],[{"name":"a"},{"child":"b"}],[{"name":"c"},{"child":"d"}]]

Answer

Add array instead of both items at once

foreach($tests as $test){
     if($test=='true') {
            $temp[] = ['name'=>'a', 'child'='b'];
         }
        else{
            $temp[] = ['name' => 'c', 'child'='d'];
        }
    }
prtint_r($temp);