Andy Holmes Andy Holmes - 6 months ago 17
PHP Question

Compare Key : Value in JSON object 1 to Key : Value in JSON object 2 and if condition matches, alter the Value

I have 2 JSON objects, one for Male Genetics and one for Female Genetics. These are shown below:

Male:

$male='{
"Bell-Albino":"Bb",
"Rainwater-Albino":"null",
"Tremper-Albino":"null",
"Murphys-Patternless":"null",
"Eclipse":"Ee",
"Marble-Eye":"null",
"Blizzard":"Zz",
"Mack-Snow":"Mm",
"Super-Snow":"null",
"Gem-Snow":"null",
"TUG-Snow":"null",
"Line-Bred-Snow":"null",
"Enigma":"null",
"White-and-Yellow":"null",
"Wildtype":"null",
"Giant":"null"
}';


Female:

$female='{
"Bell-Albino":"BB",
"Rainwater-Albino":"null",
"Tremper-Albino":"null",
"Murphys-Patternless":"null",
"Eclipse":"null",
"Marble-Eye":"null",
"Blizzard":"zz",
"Mack-Snow":"mm",
"Super-Snow":"null",
"Gem-Snow":"null",
"TUG-Snow":"null",
"Line-Bred-Snow":"null",
"Enigma":"null",
"White-and-Yellow":"null",
"Wildtype":"null",
"Giant":"null"
}';


If we take the
Eclipse
key
from the
Male
object, we have
"Eclipse":"Ee"
and if we do the same for the
Female
object we have
"Eclipse":"null"
.

In the genetics I use
EE
to signify dominant,
Ee
to signify recessive and
ee
to signify null but can be used in gene calculation.

What I need to do on the fly, is check the
keys
for the 2 objects and if one object has a
key
(
Eclipse
for example) that has a value that is not
"null"
(which means it could be
EE or Ee
) it needs to check the other object and replace the
null
value in the other object with lowercase letters like
ee
.

I know of array intersect (when using arrays) but I'm not even sure that would be the right thing to use anyway?

This is quite difficult for me to explain, and code, so apologies for waffling a bit. If I need to clarify anything please say so.

RST RST
Answer
//convert to arrays
$male = json_decode($male, true);
$female = json_decode($female, true);

foreach( $male as $key => $value ) {
  if ( $value != 'null' && $female[$key] == 'null' ) {
      $female[$key] = strtolower($value);
  } else {
    if ($female[$key] != 'null' && $value == 'null')
      $male[$key] = strtolower($female[$key]);
  }
}