-1

I tried to add a key and its in a 2D array using a foreach. The problem is that this key isn't "saved". As soon as I try to look the first array, the key I added disappeared.

There is the code :

    $Etapes=$this::getEtapes();
    foreach($Etapes as $Etape){
        $req = $this::getSuiviEtapes();
        $Etape['Nom_Suivi'] = $req[0]['Nom_Suivi'];
        if($Etape['ID_Etat_Etape']=="22")
        {
            var_dump($Etape);
            var_dump($Etapes);
            $this->Etapes=$Etapes;
            var_dump($this->Etapes);
        }

    }

And there is the return

array(3) {
  ["ID_Etat_Etape"]=>
  string(2) "22"
  ["Nom"]=>
  string(36) "Comparatif"
  ["Nom_Suivi"]=>
  string(8) "En_cours"
}
array(2) {
  [0]=>
  array(2) {
    ["ID_Etat_Etape"]=>
    string(2) "21"
    ["Nom"]=>
    string(12) "Etude"
  }
  [1]=>
  array(2) {
    ["ID_Etat_Etape"]=>
    string(2) "22"
    ["Nom"]=>
    string(36) "Comparatif"
  }
}
array(2) {
  [0]=>
  array(2) {
    ["ID_Etat_Etape"]=>
    string(2) "21"
    ["Nom"]=>
    string(12) "Etude"
  }
  [1]=>
  array(2) {
    ["ID_Etat_Etape"]=>
    string(2) "22"
    ["Nom"]=>
    string(36) "Comparatif"
  }
}

as you can see, the "Nom_Suivi" key do not appear in the second and third array.

I don't know if my issue is clear enough. Ask if it isn't. Thank you for helping.

Mric
  • 3
  • 3
  • Yup, I saw this one. I just didn't used the right keywords to search it at first. Thank you – Mric Feb 13 '18 at 10:08

2 Answers2

0

If you want to modify array you are iterating over with foreach, you either have to use reference - foreach($Etapes as &$Etape) or (prefered way) change the value by using the original array variable and key:

foreach($Etapes as $key => $Etape){
    ...
    $Etapes[$key]['Nom_Suivi'] = $req[0]['Nom_Suivi'];
    ...
}
Jan Holas
  • 278
  • 2
  • 11
0

Try using

foreach ($fields as $key => $field)

Use the key Check out this Duplicate of this question

Richard
  • 1,057
  • 1
  • 10
  • 22