Reputation: 1174
I have the following code to iterate through json array and change the value in the array.
<?php
$json='[{"type":"dropdown","label":"Is the property tenanted ?","req":0,"choices":[{"label":"Yes","sel":0,"notification":0,"subOptions":[{"NoteLabel":"Real Estate Agency ?","NoteValue":"","reqNote":"1"},{"NoteLabel":"Agents Mobile Number:","NoteValue":"","reqNote":"1"},{"NoteLabel":"Agents Email:","NoteValue":"","reqNote":"0"},{"PhotoLabel":"Attach a photo","PhotoValues":"","reqPhoto":"1"},{"NoteLabel":"Tenants Contact Number:","NoteValue":"","reqNote":"0"}]},{"label":"No","sel":1,"notification":0,"subOptions":[{"NoteLabel":"Clients Contact Number:","NoteValue":"","reqNote":"1"},{"PhotoLabel":"Attach a photo","PhotoValues":"","reqPhoto":"1"}]},{"label":"N\/A","sel":0,"notification":0,"subOptions":[]}]}]';
echo $json."<br/>";
echo "<br/><br/><br/>****************<br/><br/><br/>";
$json=json_decode($json,true);
foreach($json as $kSub => $vSub)
{
if( in_array($vSub['type'], ["dropdown"]))
{
if($vSub['label']=="Is the property tenanted ?")
{
$choices=&$vSub['choices'];
foreach($choices as $keyChoice=>&$valChoice)
{
if($valChoice['label']=="Yes")
{
$subOptions=&$valChoice['subOptions'];
foreach($subOptions as $kop=>&$Opval)
{
foreach($Opval as $kn=>&$vn)
{
if($kn=="NoteLabel")
{
if($vn=="Real Estate Agency ?")
{
$subOptions[$kop]['NoteValue']="DOMAIN";
}
}
}
}
}
}
}
}
}
echo json_encode($json)."<br/>";
I want to change the NoteValue
inside subOptions
array if the conditions are met. I am not sure whether I am doing it right or not, but the value is not changing. Please help me to sort out what I am doing wrong! I was also wondering whether I can reduce the number of code lines to get the result?
Upvotes: 0
Views: 57
Reputation: 781964
You need to use &vSub
to make it a reference variable.
You can shorten the code by getting rid of the last loop, and just access the NoteLabel
index directly. You can also combine the first two tests with &&
. And you don't need any of the index variables in your foreach
loops.
foreach($json as &$vSub)
{
if($vSub['type'] == "dropdown" && $vSub['label']=="Is the property tenanted ?")
{
$choices=&$vSub['choices'];
foreach($choices as &$valChoice)
{
if($valChoice['label']=="Yes")
{
$subOptions=&$valChoice['subOptions'];
foreach($subOptions as &$Opval)
{
if (isset($Opval['NoteLabel']) && $Opval['NoteLabel'] == "Real Estate Agency ?")
{
$Opval['NoteValue']="DOMAIN";
}
}
}
}
}
}
Upvotes: 1