-2

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"}]]

paranoid
  • 6,799
  • 19
  • 49
  • 86

4 Answers4

3

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);
splash58
  • 26,043
  • 3
  • 22
  • 34
2

reuse your $tests key to get same key when assign value...

foreach($tests as $k=>$test){
     if($test=='true') {
            $temp[$k]['name']='a';
            $temp[$k]['child']='b';
         }
        else{
            $temp[$k]['name']='c';
            $temp[$k]['child']='d';
        }
    }
    var_dump($temp);
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
1

It's quiet simple, each time php reads $array[] it reads it as a new array key,

$array[] = 1; //Key 0
$array[] = 2; //Key 1
$array[] = 3; //Key 2
$array[] = 4; //Key 3

To assign / control the key you can use multiple methods, one of the simpler ones are like so.

$i = 0;
foreach($array as $value){
    $array[$i]['name'] = 'Jamie'; 
    $array[$i]['age'] = 1;

    $i++;
}

Each time the foreach loop runs the $i variable will increase and assign your array a new key on each run through.

Result:

Array
(
    [0] => Array(
       [name] => Jamie
       [age] => 1
    )
    [1] => Array(
       [name] => Jamie
       [age] => 1
    )   
)
Epodax
  • 1,828
  • 4
  • 27
  • 32
1
$i = 0;
foreach ($tests as $test) {
  if ($test == 'true') {
    $temp[$i] = array('name' => 'a', 'child'='b');
  } else {
    $temp[$i] = array('name' => 'c', 'child'='d');
  }
  $i++;
}
prtint_r($temp);
Matiratano
  • 62
  • 6