Is it possible to find this in a foreach?

Asked

Viewed 44 times

2

I have the following script:

$arr = [
   10 => [
      'Xa' => 'xA'
   ],
   32 => [
      'Xb' => 'xB'
   ],
   45 => [
      'Xc' => 'xC'
   ],
   78 => [
      'Xd' => 'xD'
   ]
]
foreach($arr as $var){

   if($var['Xa'] == 'xA'){
      //Nesta escapatória encontrar 'this' para modificar $arr[10] 
   }
}
  • It is possible to find 'this' inside if unused 'key' ?

The context of the question is that in a given loop (from a nonsequential ascending array) I need to add data to this array, and I cannot access its key because some unsets are given at the time of construction.

It previously worked with this (before adding the unsets), but is no longer working and is adding keys that no longer exist in the array:

$c = 0;
foreach ($return as $rs_row) {
    foreach ($rs_flag as $flag) {
        if ($rs_row['id'] == $flag['relationship']) {
            $return[$c]['flag'] = $flag['flag'];
            $return[$c]['flag-cod'] = $flag['cod'];
            $return[$c]['flag-observations'] = $flag['observations'];
        }
    }
    $c += 1;
}
  • 1

    Already asked this here. I think it was Wallace. I’ll look. Only the "focus" was to rescue the content in a loop...

  • @Jeffersonquesado knows the link to this question ? I just thought to find the Dice, I can’t/I don’t want this because the indexes are scrambled, I need to somehow find 'this' or redo the part that builds this array so that it keeps the sequence.

  • It might help: https://answall.com/a/154082/64969; not exactly a duplicate, I was wrong... but it shows how to transform a array in a key/value pair, which I believe is positive for your case

  • you want to take the Input of the current element? key() or array_keys() do not help?

1 answer

2


The solution was found right after the question, just add the key pickup:

foreach ($return as $rs_key => $rs_row) {
    foreach ($rs_flag as $flag) {
        if($rs_row['id'] == $flag['relationship']) {
            $return[$rs_key]['flag'] = $flag['flag'];
            $return[$rs_key]['flag-cod'] = $flag['cod'];
            $return[$rs_key]['flag-observations'] = $flag['observations'];
        }
    }
}

Another however, by inattention I was missing the syntax:

  • Correct

    foreach($arr as $key => $target) {
        //
    }
    
  • Wrong (as I was doing)

    foreach($arr as $key -> $target) {
        //
    }
    

with this I received an error and concluded that I could not access the array erroneously.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.