Relate the indices (keys) of an obejto Array to the indices (keys) of an array (PHP)

Asked

Viewed 18 times

-1

I have a question where I could not find a solution. I have an Array object values and an array status, where I want to relate the indexes of the Array object values to the indices of the array status. So that I can write a logical test where: If the 0 of Array object values is different from null (i.e., contains value), so Dice 0 array status will receive the value '1'.

OR

If the 1 of Array object values is different from null (i.e., contains value), so Dice 1 array status will receive the value '1'.

For example, before the logical test:

values:[
 0 => Array1:[
  0 => "1,023"
  1 => "0,023"
  2 => "5,023"
  3 => "1"
 ]
 1 => Array2:[
  0 => "null"
  1 => "null"
  2 => "5"
  3 => "1,365"
 ]
 2 => Array3:[
  0 => "null"
  1 => "null"
  2 => "null"
  3 => "null"
 ]
]


status:[
 0 => "0"
 1 => "0"
 2 => "0"
]

After the logical test:

status:[
 0 => "1"
 1 => "0"
 2 => "0"
]

In this example only the Indice 0 array status received the value "1", because ONLY the array 0 of Array object values had values other than null.


Remarks:

The array status will always have the same number of indexes as the Array object values will have to arrays (Array status has 5 indices (0, 1, 2, 3, 4), the Array object value will have 5 arrays (0, 1, 2, 3, 4)). Also the array status always start with the value of the Dice equal to '0'. What if the values of the object indices values are ALL different from null, each array input status will receive the value '1'.

Exemplifying,

status:[
 0 => "1",
 1 => "1",
 2 => "1",
]

I tried to use an if to go through the indices (keys) of the array object value and an if to change the values of status. I even used other variations, but nothing that worked

<?php

foreach ($value as $key => $items) {
  if ($items ==  "null") {
   $status['status'][$key] == "0";
 } else {
   $status['status'][$key] == "1";
 }
}

?>

I hope I’ve been clear in my doubt.
From now on, thank you.

1 answer

-1

After a lot of testing and reading of the PHP documentation, I can solve my problem.


foreach ($values as $key => $items) {
    if (in_array(null, $items)) {
        $status['status'][$key] = "0";
    } else {
        $status['status'][$key] = "1";
    }
}

When I give a dd($status) I get confirmation of the desired modification.


"status" => [
 0 => "1"
 1 => "0"
 2 => "0"
]

Browser other questions tagged

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