我在mysql数据库表中有一个json格式的数据,如下所述。
{
"dataType": "mis_type",
"diceCode": "20070100102",
"forms": {
"4. Campus": {},
"7. Classroom": {},
"1. Details of school": {
"School_Name": "GOVT. UPG .M.S. KHAGARA",
"Village_Name": "KHAGARA",
"Block_Name": "MOHAN PUR",
"Dist_Name": "DEOGHAR",
"Type_of_School": "DEPARTMENT OF EDUCATION",
"Category": "PRIMARY WITH UPPER PRIMARY",
"No_of_Student": 209,
"No_of_Section": 8,
"No_of_Classroom": 5,
"Govt_Teacher": 2,
"Para_Teacher": 3,
"Other_Teacher": 0,
"Total_Teacher": 5,
"Total_Toilet": 2,
"Total_Urinals": 2
},
"6. Drinking Water Source": {},
"8. Kitchen Shed": {},
"2. Location of School": {},
"5. Location of Toilet": {},
"3. Pollution Status": {
}
}
}
我正在尝试从另一个新值替换“Total_Toilet”值。为此,我写了下面的代码。
$selectQuery = "SELECT `json_data` FROM `abc` WHERE `disc_code`='" . $diseCode . "' AND `type`='mis'";
$res = $conn->query($selectQuery);
$jsonvalue = $res->fetch_assoc();
$jsonvalue = json_decode($jsonvalue['json_data'], true);
unset($value['Dise_Code']);
unset($value['OBJECTID']);
if ($res->num_rows > 0)
{
foreach( $jsonvalue['forms']['1. Details of school'] as $key1 => $value1 )
{
echo"<br>";
$key2 = str_replace($jsonvalue['forms']['1. Details of school'] ['Total_Toilet'] , 4, $value1 ) ;
echo $key2;
}
正在编译代码时没有任何错误,但仍然使用str_replace函数将以前的值替换为新值。 如果我有什么问题,那么请指导我,或者如果有任何其他解决方案,请帮助我。
任何帮助都将不胜感激。
答案 0 :(得分:1)
好的,请在foreach循环之前添加以下行
$jsonvalue['forms']['1. Details of school']['Total_Toilet'] = 4;
将foreach循环设为如下
foreach( $jsonvalue['forms']['1. Details of school'] as $key1 => $value1)
{
echo"<br>";
$key2 = $value1;
echo $key2;
}
我希望这会对你有所帮助。
答案 1 :(得分:0)
请更改您的foreach循环,如下所示更新您的数据库
foreach($jsonvalue['forms']['1. Details of school'] as $key1 => $value1 )
{
$current_value = $jsonvalue['forms']['1. Details of school']['Total_Toilet'];
$new_value = '12'; // Replace with new value that you want
echo $new_json = str_replace('"Total_Toilet": '.$current_value.'','"Total_Toilet": '.$new_value.'',$jsonvalue['json_data']);
echo "<hr>";
$updateQuery = "update `abc` set `json_data` = '".$new_json."' WHERE `disc_code`='" . $diseCode . "' AND `type`='mis'";
$res = $conn->query($updateQuery);
}
注意:根据您的要求编辑查询中的变量。可以随意发表评论。